我正在创建一个数组,其中包含我需要随机选择的描述(字符串)列表,然后分配给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);
}
}
答案 0 :(得分:2)
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;
}
}
答案 1 :(得分:1)
string myString = animalDescriptions[new Random().Next(animalDescriptions.Length)];
您可能希望将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()
}