- Home /
How do I get a list to randomly select....
How do I get a list to randomly select and output a string? I am trying to make a List that has my Answer Strings randomly select an answer and output to the label for the button. I have not used lists in quite awhile so I an drawing a blank
here is some of the code to help
The Button
if(GUI.Button(buttonSizeA, "A")) // make a button
{
print ("Button A");
WaipointCounter = 4;
}
GUI.Label (AnswerSizeA, choices(0));
The List
public void GetAnswer()
{
List<string> choices = new List<string>(4);
choices.Add(AnswerStringA);
choices.Add(AnswerStringB);
choices.Add(AnswerStringC);
choices.Add(AnswerStringD);
}
Thank you for your time and help in advance.
Answer by Cherno · Nov 19, 2013 at 09:07 PM
RandomString = choices[Random.Range(0, Mathf.Round(choices.Count - 1))];
how would I add it to the button so that the string would show up and how can I keep it from repeating
No repeating:
choices.Remove(RandomString);
You can show the string just as any other GUI.Label.
No. choices.Remove(RandomString); is supposed to go after assigning the RandomString; It removes this string from the list so it won't get chosen again next time.
In the GUI.Label code, you would just use RandomString, which is the variable in which your randomly chosen string is stored.
The documentation says Random.Range is max exclusive for integers, so it should be choices[Random.Range(0,choices.Count)]
. Also I don't think you would need the $$anonymous$$athf.Round
if you're just dealing with all integers.
WilliamLeu:
Ah yes I forgot that Random.Range also handles integers. In this case, the $$anonymous$$athf.Round is indeed not needed:
RandomString = choices[Random.Range(0, choices.Count - 1)];
Jsyoung:
Where is your problem? you have the string, just insert it in your GUI.Label code and it will work.
If you are not sure about the syntax of how GUI.Label, refer to the Unity3D user reference.
http://docs.unity3d.com/Documentation/ScriptReference/GUI.Label.html
GUI.Label(YourLabelPosition, RandomString);