2016-03-07 48 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

这是一个问题吗?如果您三次实例化按钮,则会得到三个新对象,请更正。 –