简体   繁体   English

在统一C#脚本中从预制创建按钮

[英]Create button from a prefab in a unity C# script

I am running a foreach loop, adding a debug.log, but instead of that I want it to create a button, from a prefab I have from the rest of the game, and change the text of the button, based on what it says in the array. 我正在运行一个foreach循环,添加一个debug.log,但是与其相反,我希望它从游戏其余部分的预制件中创建一个按钮,并根据其内容更改按钮的文本在数组中。

My current script: 我当前的脚本:

string webResults = www.text;
char seprator = '\t';
string[] myStringArray = webResults.Split(seprator);

foreach(string i in myStringArray)
{
    Debug.Log(i);
}

Thanks, Ethan! 谢谢,伊桑!

First, create a Canvas . 首先,创建一个Canvas Your Buttons must be created as the child in it. 您的按钮必须作为其子级创建。

Now, in your code: 现在,在您的代码中:

using UnityEngine.UI;

....

public Canvas canvas
public Button btnPrefab;

....

string webResults = www.text;
char seprator = '\t';
string[] myStringArray = webResults.Split(seprator);

foreach(string i in myStringArray)
{
    Button newBtn = Instantiate(btnPrefab, canvas.transform, false);
    newBtn.GetComponent<RectTransform>().anchoredPosition = // position you want...
    newBtn.GetComponentInChildren<Text>().text = i;
}

I hope it helps you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM