2016-08-15 59 views
0

我是c#和Unity中的新手,但我一直在想是否可以實例化一個文本,以便其內容將對應於從檢查器編輯的字符串數組?具有不同屬性的實例化文本克隆?

我的意思是這樣的:

文本(你好)TextClone1(有)TextClone2(你好嗎)TextClone3(再見)

而且所有的文本(內容)到可以直接從檢查員編輯,所以最終它看​​起來像來自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)); 
    } 
+0

我猜你正在做的不錯。給定的代碼有什麼問題? –

+0

以及我想實例化文本對象,以便字符串數組對應於它:array [i] = text [i] – Sciencephile

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

很好用!謝謝!現在我必須弄清楚如何使文本克隆出現在以前的文本之下。 – Sciencephile

+0

使用VerticalLayoutGroup:https://docs.unity3d.com/Manual/script-VerticalLayoutGroup.html –

相關問題