- Home /
C# Random String Array help
void OnGUI(){
string[] splashes = {"Less than one sold!", "lol","lmao","what?"};
System.Random random = new System.Random();
string quote = splashes[random(splashes)];
GUI.Label(new Rect(50,500,300,100),quote);
}
//I'm trying to create a GUI which will have random sentences in the splashes string. I have no idea how to do this, but can someone please find a way on how to do this? So for example, when I start up the game, it will state "Less than one sold!", "lol", "lmao", or "what?". If you have every played Minecraft where there are those hundreds of different yellow sentence splashes at an angle, then you should know I want.
What is the problem with the code you have posted? Looks like you're doing it already.
Answer by Eric5h5 · Sep 26, 2012 at 10:57 PM
To make things easier, use Random.Range (look it up in the Unity docs), and you should only do it once, in Start or whatever, not every frame in OnGUI, otherwise it will constantly flicker between random strings.
facepalm I didn't notice the OnGUI part - especially nasty with the `new`. But what's the point of using Random.Range? I suppose Unity uses its own internal System.Random singleton that way, so you won't risk running into the issues associated with multiple Random instances, but are there any other benefits?
As I mentioned, it's easier.
string quote = splashes[Random.Range(0, splashes.Length)];
Unity doesn't use System.Random for that, by the way; they use their own routine. In some cases where you need more control it would be appropriate to use System.Random, but for typical general randomness, UnityEngine.Random is somewhat simpler to work with.
Answer by Jesdisciple · Sep 26, 2012 at 10:18 PM
You almost had it. See here: http://msdn.microsoft.com/en-us/library/zd1bc8e5.aspx
That method returns an integer from 0 up to but not including `maxValue`, perfect for use as an index for an array of size `maxValue`. Your modified code would be:
string quote = splashes[random.Next(splashes.Length)];
I should note that I didn't run this code; I'll gladly correct it if necessary.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081528im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
holding GUITextures in a array? and changing the size from script? 2 Answers
Multiple Cars not working 1 Answer
GUISttyle NullReferenceException error. what am I missing ? 1 Answer
How to select an Game Object from an Item List 0 Answers
One variable set TRUE when another must be false. TOGGLE 3 Answers