具有不同属性的实例化文本克隆?

时间:2016-08-15 09:01:19

标签: c# arrays unity3d text instantiation

我是c#和Unity的新手,但我一直想知道是否可以实例化文本,以便其内容对应于从检查员编辑的字符串数组?

我的意思是:

  

Text(Hello)TextClone1(There)TextClone2(你好吗)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));
    }

1 个答案:

答案 0 :(得分:2)

试试这段代码:

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++;
}