2013-12-20 52 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