Reputation: 1348
I'm creating an array with a list of descriptions (strings) that I need to choose randomly and then assign to a text component in a gamobject. How do I do that? I've created the array but I don't know where to go from there. Can anyone help me with this?
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);
}
}
Upvotes: 0
Views: 2534
Reputation: 926
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;
}
}
Upvotes: 2
Reputation: 9270
string myString = animalDescriptions[new Random().Next(animalDescriptions.Length)];
You might want to store that new Random()
somewhere else so that you don't seed a new one every time you want a new random description, but that's about it. You can do that by initializing your Random
elsewhere, and simply using your instance of it in Start
:
Random rand = new Random();
// ... other code in your class
void Start()
{
string myString = animalDescriptions[rand.Next(animalDescriptions.Length)];
// ... the rest of Start()
}
Upvotes: 1