- Home /
Setting variable to random string from an array?
I'm looking to assign a name to each "person" variable by randomly selecting a string from an array of names I've created.
var person1;
var person2;
var person3;
var firstNames = new Array ();
function Start () {
firstNames = ["Brian","Paul","George","Jacob","Richard"];
person1 = getRandomFirstName();
person2 = getRandomFirstName();
person2 = getRandomFirstName();
}
function getRandomFirstName() {
return firstNames[Random.Range(0,firstNames.Length)];
}
But when I run this code I get this error:
NullReferenceException: Object reference not set to an instance of an object
Boo.Lang.Runtime.RuntimeServices.CheckNumericPromotion(IConvertible convertible)
Can anyone help me out?
well your range is wrong, it should be 0 to firstNames.Length-1
But Im not sure thats your problem. I'm not incredibly versed in UnityScript. i do everything in C#.
The range is not wrong actually. Random.Range excludes the high value with int but includes it with float. API
Answer by NoseKills · May 18, 2014 at 12:37 AM
In JS scripts it has to be firstNames.length
- "length" with a lower case "l".
Your compiler doesn't even check for that error because you don't have "#pragma strict" as the first line in your class file. Might be a good practice to at least momentarily put that line in if you run into problems. It might lead you to the right tracks when debugging.
Also you're not setting the value of person3 anywhere, but you set person 2 twice, which leaves person 3 as null (might cause future problems)
Your answer
Follow this Question
Related Questions
String Access problem 1 Answer
how to randomly pick a string from an array 3 Answers
Referencing private string for array name 2 Answers
How to randomize an array of Strings? 2 Answers
Assigning array element to variable 1 Answer