2013-12-20 73 views
3

修复我试图访问另一个脚本中包含的类,我得到这个:“Internal_Create只能从主线程调用”。 .init函数只是改变类中的一些值。Unity3d:通过GetComponent错误从另一个脚本访问类

我试图通过搜索答案来解决它,但我找不到任何有用的东西。

这是发生错误的主循环:

public class MainLoop : MonoBehaviour { 

public float jagginess; 


void Start() { 
    jagginess = 0.6f; 
    CMesh cmesh = GameObject.Find("GameObject").GetComponent<CMesh>(); 
    cmesh.init(32); 

} 


void Update() { 

    //if (Input.GetKeyDown(KeyCode.Space)) { 

} 

}和网格类:

[RequireComponent(typeof(MeshFilter))] 
[RequireComponent(typeof(MeshRenderer))] 
[RequireComponent(typeof(MeshCollider))] 

public class CMesh : MonoBehaviour { 

     Mesh mesh = new Mesh(); 

     Texture2D heightMap; 

     int segments; 
     Vector3 scaleSegments; 

     Vector3[] vertices; 
     Vector3[] normals; 
     Vector2[] uv; 
     int[] triangles; 

     Vector3 camera_position = GameObject.Find ("Main Camera").GetComponent<cameraMovement>().camera_pos; 

     public void init(int mesh_segments) { 

      scaleSegments = new Vector3(200, 100, 200); 

      segments = mesh_segments; 

      initHeightMap(); 
     } 
+0

@Burdock '使用UnityEngine;使用System.Collections的 ; public class MainLoop:MonoBehaviour { \t \t public float jagginess = 0.6f; \t \t \t空隙开始(){ \t \t \t \t CMesh cmesh =(CMesh)gameObject.GetComponent (); \t \t cmesh.init(32); \t \t \t } \t \t空隙更新(){ \t \t \t // \t如果(Input.GetKeyDown(密钥号码。空间)){ \t \t} }' – whoadrian

+0

在评论中发布大量代码并不是一个好主意。你可以随时编辑你的文章。这就是说,你的班级没问题。看看我的答案,它应该解决你的问题。 – 2013-12-21 00:59:41

+0

'使用UnityEngine;使用System.Collections的 ; [RequireComponent(typeof运算(MeshFilter))] [RequireComponent(typeof运算(MeshRenderer))] [RequireComponent(typeof运算(MeshCollider))] 公共类CMesh:MonoBehaviour { \t \t网目=新目() ; \t \t \t \t Texture2D heightMap; \t \t \t \t int segments; \t \t的Vector3 scaleSegments =新的Vector3(200,100,200); \t \t \t \t \t \t \t 的Vector3 \t = camera_position GameObject.Find( “主相机”)GetComponent ()camera_pos。; \t \t \t公共无效的init(INT mesh_segments){ \t \t \t \t \t \t段= mesh_segments; \t \t \t \t \t initHeightMap(); \t \t} \t \t' – whoadrian

回答

1

您需要在使用之前每次问自己这个问题GetComponent()什么GameObject包含您正在查找的脚本?

一旦你知道游戏对象的名称,如果脚本连接到不同的游戏对象,你可以这样做:

CMesh cmesh = GameObject.Find("NameOfGameObject").GetComponent<CMesh>();

如果脚本连接到你可以这样做同样的游戏对象:

CMesh cmesh = GetComponent<CMesh>();

+0

请注意,这已经得到解决,这个问题不具有参考这个做.gameObject – Burdock

+0

您一直在错误地解决该问题。实际上说'this.gameObject'是多余的。我的代码肯定会有效。 – 2013-12-21 00:53:46

-2

你错过了铸造部件。尝试: CMesh cmesh =(CMesh)gameObject.GetComponent < CMesh>();

在此之前,请确保您要访问的脚本位于同一个对象上。否则,您需要首先获取该对象,然后获取组件:

CMesh cmesh =(CMesh)GameObject.Find(“The Object Name here”)。GetComponent < CMesh>();

第二个总是适合我。

我希望这有助于。

干杯!

+0

团结,GetComponent ()不需要铸造,因为它是一个通用 – Burdock