具有不同属性的实例化文本克隆
本文关键字:实例化 文本 属性 | 更新日期: 2023-09-27 18:02:29
我是c#和Unity的新手,但我一直在想是否有可能实例化文本,以便其内容对应于字符串数组,从检查器编辑?
我的意思是:
Text(Hello) TextClone1(There) TextClone2(How are you doing) TextClone3(Goodbye)
所有的文本(内容)都可以直接从检查器中编辑,所以最后它看起来像来自Facebook的几条消息,一个在另一个下面。
到目前为止,我的代码如下:public class Wait : MonoBehaviour {
private int i = 0;
public string[] message;
public float t;
[SerializeField]
private Text toText;
public IEnumerator Message(float waitTime = 2f)
{
toText.text = message[i];
i++;
waitTime = t;
yield return new WaitForSeconds(waitTime);
}
void Start()
{
StartCoroutine(startMessage());
}
IEnumerator startMessage()
{
yield return StartCoroutine(Message(i));
yield return StartCoroutine(Message(i));
yield return StartCoroutine(Message(i));
yield return StartCoroutine(Message(i));
}
试试下面的代码:
public Transform containor; // Assign a UI Object like panel to this variable. This will hold all text objects.
public Text textPrefab; // save a UI object (with a text component attached) as prefab in project and then assign it to this variable from inspector.
public string[] array = new string[10]; // can set values from editor/inpector window
int i = 0;
IEnumerator Start()
{
foreach (var item in array)
{
yield return StartCoroutine(ShowMessage());
}
}
IEnumerator ShowMessage()
{
yield return new WaitForSeconds(i);
Text newText = Instantiate<GameObject>(textPrefab.gameObject).GetComponent<Text>();
newText.text = array[i];
newText.transform.SetParent(containor);
i++;
}