2013-09-27 46 views
0

我想在循環中創建X對象,訪問並設置新創建對象的屬性。我已經使用了Instantiate方法和傳遞的RigidBody,如本教程中所示,但我需要訪問連接到該對象的腳本的屬性,而不僅僅是剛體。在運行時在Unity中創建類實例

這裏是我想要做的工作方法:

public void makeGrid(int w = 10, int h = 10) 
{ 
    gridWidth = w; 
    gridHeight = h; 

    int tileArrayLength = gridWidth * gridHeight; 
    tileArray = new Tile[tileArrayLength]; 

    for (int i = 0; i < gridWidth; i++) 
    { 
     for (int j = 0; j < gridHeight; j++) 
     { 
      // add tiles 
      Tile t = new Tile(); // !!! doesn't work >_< 
      t.posX = i; 
      t.posY = j; 
      t.id = j + 10 * i; 

      tileArray[t.id] = t; 
     } 
    } 

} 

回答

2

我想創建一個循環,獲得X對象和 新創建的對象的設置屬性。

您可以創建通過編輯器預製件,然後實例化它們,或者明確地創建一個GameObject,重視你需要它的組件:

GameObject prefabInstance = GameObject.Instantiate(Resource.Load("path_to_prefab")) as GameObject; 

GameObject instanceThroughReference = GameObject.Instantiate(aReferenceToAnInstantiableObject) as GameObject; 

GameObject emptyGameObject= new GameObject("empty game object"); 

爲了什麼顧慮:

我我已經使用了實例化方法和傳遞的RigidBody,如本教程中顯示的 ,但我需要訪問連接到該對象的腳本 的屬性,而不僅僅是剛性的 身體。

有財產我想你的意思是Components附加到GameObject實例化。 如果您通過參考實例化對象或通過Resources.Load加載,如果原始GameObject具有要附加到其上的組件,則可以使用GetComponent方法檢索它們,或捕獲AddComponent的返回值。

如果要創建一個空的GameObject,你必須明確地附上Components你需要:

GameObject go = new GameObject("foo"); 
Bar bar = go.AddComponent<Bar>(); //where Bar extends MonoBehavior 
相關問題