[英]Add buttons programmatically Unity C#
I am trying to create button in C# code using an existing Prefab. 我正在尝试使用现有的Prefab在C#代码中创建按钮。 All I found on the website was something like
我在网站上发现的所有东西都像
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>();
}
}
In Unity project I have Prefab called "ButtonPrefab" where I put Button Object. 在Unity项目中,我放置了名为“ ButtonPrefab”的Prefab,并在其中放置了Button Object。 There is an error in below line
下一行有错误
UnassignedReferenceException: The variable a of NewBehaviourScript has not been assigned.
UnassignedReferenceException:未分配NewBehaviourScript的变量a。 You probably need to assign the a variable of the NewBehaviourScript script in the inspector.
您可能需要在检查器中分配NewBehaviourScript脚本的变量。
I am new to Unity. 我是Unity新手。 How is it come that not assigned var a can give me button using Instantiate()?
为什么未分配的var a可以使用Instantiate()给我按钮? And why do I have this error?
为什么我会有这个错误?
You can instantiate prefabs very easily from within a Resources folder. 您可以从Resources文件夹中非常容易地实例化预制件。 Make a new folder within your project's Assets folder called Resources.
在项目的Assets文件夹中新建一个名为Resources的文件夹。 It must be named Resources for this to work properly.
它必须命名为Resources才能正常工作。 Then you can make your button like this:
然后,您可以像这样制作按钮:
GameObject button = Instantiate(Resources.Load("myButton", typeof(GameObject))) as GameObject;
Assuming your prefab is named "myButton." 假设您的预制名为“ myButton”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.