Paul Balan Paul Balan - 3 months ago 14
C# Question

Instantiated text clones with different properties?

I'm a newbie in c# and Unity, but I have been wondering whether it is possible to instantiate a text, so that its content will correspond to a string array, edited from the inspector?

What I mean is like:


Text(Hello) TextClone1(There) TextClone2(How are you doing) TextClone3(Goodbye)


And all of the Text(Content) to be directly editable from the inspector, so that in the end it would look like several messages from Facebook, one under another.

The code I have so far is the following:

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

Answer

Try this code:

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