- Home /
Javascript - Calling a random String
Trying to just call a random string from an array in Javascript. Apparentlyyyy I'm missing two semicolons? Can't seem to spot where though. All this is trying to do it print a random string from the 'names' array. Not to sure if the code works or not since I am getting this stupid error. Thank you!
var names: String["name1", "name2", "name3"];
int i = Random.Range(0, names.Length - 1);
var name = names[i];
function Update ()
{
print("name");
}
Answer by Montraydavis · Oct 14, 2012 at 01:09 PM
StringContainer [ 0 ] = "google" ;
StringContainer [ 1 ] = "yahoo" ;
StringContainer [ 2 ] = "ask" ;
StringContainer [ 3 ] = "bing" ;
function Update ( ) {
print ( StringContainer [ Random.Range ( 0,3 ) ] ) ; // Will choose a random number between 0-3
}
You can also take a look at
Random () in the SDK .... IE Random.Value ( ) ;
Random.Range(0,3) does not choose a random number between 0-3. The numbers you will get are 0, 1, and 2.
Answer by Eric5h5 · Oct 14, 2012 at 04:16 PM
You have a number of errors...the array is declared incorrectly, you have code outside a function that should not be, Random.Range is used incorrectly, and the print statement is using quotes incorrectly.
var names = ["name1", "name2", "name3"];
function Start ()
{
var i = Random.Range (0, names.Length);
var name = names[i];
print (name);
}