2016-03-07 75 views
0

我試圖使用現有的預製建立在C#代碼按鈕。所有我在網站上發現了類似添加按鈕編程統一C#

public GameObject a; 
public RectTransform ParentPanel; 
void Start() 
{ 
    for (int i = 0; i < 5; i++) 
    { 
     GameObject goButton = (GameObject)Instantiate(a); /error 
     goButton.transform.SetParent(ParentPanel, false); 
     goButton.transform.localScale = new Vector3(1, 1, 1); 
      Button tempButton = goButton.GetComponent<Button>(); 
    } 
} 

在Unity項目中,我有預製稱爲「ButtonPrefab」這裏我把按鈕對象。在下面的行中有錯誤

UnassignedReferenceException:NewBehaviourScript的變量a尚未分配。 你可能需要分配NewBehaviourScript腳本變量的檢查。

我是新來統一。怎麼會沒有分配var a可以使用Instantiate()給我按鈕?爲什麼我有這個錯誤?

+0

如果它只是爲了調試,你可能會逃脫這個http://docs.unity3d.com/ScriptReference/GUI.Button.html – slf

+0

你是否從編輯器中拖動和跳轉GameObject? –

回答

0

您可以從一個資源文件夾中很容易實例預製件。在項目的Assets文件夾中創建一個名爲Resources的新文件夾。它必須命名爲資源才能正常工作。然後你可以使你的按鈕是這樣的:

GameObject button = Instantiate(Resources.Load("myButton", typeof(GameObject))) as GameObject; 

假設你的預製件被命名爲「myButton」。

+0

您好所以這個循環之後,我有3個新GameObjects?對(INT I = 0; I <3; i ++在) { VAR鍵=實例化(Resources.Load( 「myButton的」 的typeof(遊戲物體)))作爲遊戲對象; – miechooy

+0

這是一個問題嗎?如果您三次實例化按鈕,則會得到三個新對象,請更正。 –