【问题标题】:Instantiated text clones with different properties?具有不同属性的实例化文本克隆?
【发布时间】:2016-08-15 09:01:18
【问题描述】:

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

【问题讨论】:

  • 我猜你做得很好。给定的代码有什么问题?
  • 好吧,我想实例化文本对象,以便字符串数组与其对应:array[i] = text[i]
  • 你的代码没有这样做?
  • 嗯不,我什至没有实例化文本 obj。我不知道如何使它成为 array[i] = Instantiate(text[i])

标签: c# arrays unity3d text instantiation


【解决方案1】:

试试这个代码:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2018-08-17
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 2013-12-05
相关资源
最近更新 更多