0
\$\begingroup\$

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.

\$\endgroup\$

closed as off-topic by MichaelHouse Oct 26 '15 at 18:07

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions that aren't specific to game development are off-topic here, but can be asked on Stack Overflow. A good rule of thumb is to ask yourself "would a professional game developer give me a better/different/more specific answer to this question than other programmers?"" – MichaelHouse
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ stackoverflow.com/questions/6695187/… \$\endgroup\$ – MichaelHouse Oct 26 '15 at 18:08
  • \$\begingroup\$ @Byte56 I'm using an array, not a list. \$\endgroup\$ – DubGamer87 Oct 26 '15 at 18:11
  • \$\begingroup\$ Make sure you read the question and answers. They apply to arrays. \$\endgroup\$ – MichaelHouse Oct 26 '15 at 18:13
  • \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Oct 27 '15 at 12:37
1
\$\begingroup\$
string randomString = ExampleArray[Random.Range(0, ExampleArray.Length)];
\$\endgroup\$
  • \$\begingroup\$ When I tried it, it didn't work. \$\endgroup\$ – DubGamer87 Oct 27 '15 at 8:55
  • \$\begingroup\$ Try it again it works \$\endgroup\$ – jgallant Oct 27 '15 at 9:46
  • \$\begingroup\$ can you do this in all functions(OnGUI, update, etc) \$\endgroup\$ – DubGamer87 Oct 27 '15 at 12:16
  • \$\begingroup\$ Yes... This is a single line of code that will extract a random value from your string array. \$\endgroup\$ – jgallant Oct 27 '15 at 12:17
  • \$\begingroup\$ OK. I'll try it later. I can't right now. \$\endgroup\$ – DubGamer87 Oct 27 '15 at 12:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.