Random Range Issues

Hey Guys
I am trying to make this script which chooses a random number between 1 and 10(inclusive) and then assign a string to a different variable, but when i run the game it just defaults the number to 0 and won’t change back.

#pragma strict

/*Names */
public var B1 = “Bob”;
public var B2 = “Tim”;
public var B3 = “Mike”;
public var B4 = “Dale”;
public var B5 = “John”;
public var G1 = “Mia”;
public var G2 = “Zara”;
public var G3 = “Ava”;
public var G4 = “Evie”;
public var G5 = “Savannah”;

/Shop Items/
public var Clock = 3;
public var Books = 8;
public var ToyCar = 6;
public var ToyForkLift = 3;
public var SandTimers = 2;
public var WoodenDish = 4;
public var PottedPlant = 7;
public var WhiteBoard = 1;
public var Vase = 4;
public var Wrench = 3;
public var CrowBar = 3;
public var SledgeHammer = 2;
public var Soap = 6;
public var AlarmClock = 4;
public var SilverTray = 5;

var PersonChoice = Random.Range(0f,11f);
var CurrentPerson = “”;

function Update () {
if(PersonChoice > 1 && PersonChoice < 2)
{
CurrentPerson = B1;
}

else if(PersonChoice > 2 && PersonChoice < 3)
{
CurrentPerson = B2;
}

else if(PersonChoice > 3 && PersonChoice < 4)
{
CurrentPerson = B3;
}

else if(PersonChoice > 4 && PersonChoice < 5)
{
CurrentPerson = B4;
}

else if(PersonChoice > 5 && PersonChoice < 6)
{
CurrentPerson = B5;
}

else if(PersonChoice > 6 && PersonChoice < 7)
{
CurrentPerson = G1;
}

else if(PersonChoice > 7 && PersonChoice < 8)
{
CurrentPerson = G2;
}

else if(PersonChoice > 8 && PersonChoice < 9)
{
CurrentPerson = G3;
}

else if(PersonChoice > 9 && PersonChoice < 10)
{
CurrentPerson = G4;
}

else if(PersonChoice > 10 && PersonChoice < 11)
{
CurrentPerson = G5;
}

Debug.Log(CurrentPerson);

}

"Range can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."

The error is pretty clear about what you need to do

Id also suggest you change your approach to using arrays

#pragma strict

/*Names */

public var Names : String[] =[
"Bob",
"Tim",
"Mike",
"Dale",
"John",
"Mia",
"Zara",
"Ava",
"Evie",
"Savannah"
];


var PersonChoice = 0;
var CurrentPerson  = "";

function Update () {
    PersonChoice = Random.Range(0,10);
    CurrentPerson = Names[PersonChoice];
    Debug.Log(CurrentPerson);
}
1 Like

Also if(PersonChoice > 1 && PersonChoice < 2) greater than 1 and less than 2 will never be true…

1 Like

1.5? The OP is using the float variation of Random.Range (although quite why I’m not sure!)

Yeah probably did not even have to post this, I got Frustrated yesterday and was not thinking straight. came back this morning and fixed it but thanks anyway