Hello! I’m trying to change the text of a textmesh GameObject to a random text snippet from an array of text snippets when the game starts. I’m very inexperienced with code, but here’s what I have so far:
function Start () {
GetComponent(TextMesh).text = ("hello"||"good day"||"what's up");
}
I’ve tried finding the answer, but I’ve only found examples with number ranges. Thank you in advance!
First, you’ll need a collection of items to choose from. There are many different types of collections you can read about, but the simplest for now is a built-in array:
var snippets = ["hello", "good day", "what's up"];
Second, you need to pick a random item from your array. We’ll use Unity’s Random.Range function:
//random number between 0 and length-1
var index = Random.Range(0, snippets.Length);
Third, you assign the value:
GetComponent(TextMesh).text = snippets[index];
Putting all of that together:
function Start() {
var snippets = ["hello", "good day", "what's up"];
var index = Random.Range(0, snippets.Length);
GetComponent(TextMesh).text = snippets[index];
}
If any of this confuses you, remember that you can always look up programming tutorials around the net. It’s slow going, at first, but you’ll get better at it with time.