# Choosing random array indexes in Unity C# [closed]

I want to change a string by randomly choosing an index in an array, using the random.range command in unity. Bare in mind that I'm using strings here, not floats or integers. Here is a code example(not the real thing. I'm just coming up with this by example, but it still has the same meaning. I may make a few typo errors as a result):

public string ChangingString = ("");
public string[]ExampleArray = new string [2];

void Start () {
ExampleArray[0] = ("String1");
ExampleArray[1] = ("String2");
}
void OnGUI () {
if(GUI.Button(new Rect(10,10,100,24), "Randomize text")){
ChangingString = (code to choose random string using the ExampleArray);
}
GUI.Label(new Rect(10,30,100,20), ChangingString);
}


EXTRA NOTE: I'M NEW TO USING ARRAYS.

• stackoverflow.com/questions/6695187/… – MichaelHouse Oct 26 '15 at 18:08
• @Byte56 I'm using an array, not a list. – DubGamer87 Oct 26 '15 at 18:11
• Make sure you read the question and answers. They apply to arrays. – MichaelHouse Oct 26 '15 at 18:13
• I recommend re-opening this question. It may seem to be a generic programming question sufficiently-covered by StackOverflow, but I think the Unity tag is significant here. In a Unity game it would be more conventional to use the Random.Range() static method from the UnityEngine namespace (as Jon describes in an answer below), rather than creating an instance of the System.Random class as suggested at the linked answer. – DMGregory Oct 27 '15 at 12:37

## 1 Answer

string randomString = ExampleArray[Random.Range(0, ExampleArray.Length)];

• When I tried it, it didn't work. – DubGamer87 Oct 27 '15 at 8:55
• Try it again it works – jgallant Oct 27 '15 at 9:46
• can you do this in all functions(OnGUI, update, etc) – DubGamer87 Oct 27 '15 at 12:16
• Yes... This is a single line of code that will extract a random value from your string array. – jgallant Oct 27 '15 at 12:17
• OK. I'll try it later. I can't right now. – DubGamer87 Oct 27 '15 at 12:19