[英]Random array string assigned to a text component - Unity 4.6, uGUI
[英]Assign a random array string to a text component - Unity 4.6, uGUI
我正在创建一个包含描述(字符串)列表的数组,需要随机选择这些描述(字符串),然后分配给gamobject中的文本组件。 我怎么做? 我已经创建了数组,但是我不知道从那里去哪里。 谁能帮我这个?
public string[] animalDescriptions =
{
"Description 1",
"Description 2",
"Description 3",
"Description 4",
"Description 5",
};
void Start ()
{
string myString = animalDescriptions[0];
Debug.Log ("You just accessed the array and retrieved " + myString);
foreach(string animalDescription in animalDescriptions)
{
Debug.Log(animalDescription);
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public Text myText;
public string[] animalDescriptions =
{
"Description 1",
"Description 2",
"Description 3",
"Description 4",
"Description 5",
};
void Start()
{
string myString = animalDescriptions [Random.Range (0, animalDescriptions.Length)];
myText.text = myString;
}
}
string myString = animalDescriptions[new Random().Next(animalDescriptions.Length)];
您可能希望将该new Random()
存储在其他位置,这样就不必每次都想要一个新的随机描述时就播下一个new Random()
,仅此而已。 您可以通过在其他地方初始化Random
并在Start
简单使用它的实例来做到这一点:
Random rand = new Random();
// ... other code in your class
void Start()
{
string myString = animalDescriptions[rand.Next(animalDescriptions.Length)];
// ... the rest of Start()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.