Setting a variable number once in update class

Hi guys,
I am writing a function to get a variable number, but I want to be able to call it again when desired so don’t want it only to run in the start class. When I run my code my random numbers are generated constantly because they are being called in the update class and so running once per frame…

for example I want a listener to be looking for State and then set a variable to a random number (but I only want this to happen once every time you enter the state, not on each frame…)
Thanks for any help or suggestions
sub

Can you share your code? Because I’m not understanding, What you want exactly

void pickNumbers(){

print (“picking”);
varA = Random.Range(3, 8);
varB = Random.Range(3, 8);
}

// Update is called once per frame
void Update () {
print (varA);
print (varB);
print (myState);
if (myState == States.start){
pickNumbers ();
state_start();
}else if (myState == States.start_1){
pickNumbers ();
state_start_1();
}else if (myState == States.subtraction_1){
pickNumbers ();
state_subtraction_1();
}
}

so even if I put the pickNumbers function inside the function for the states it still runs constantly every frame
when I call the picknumbers func I just want to get a random no. for varA and a random no. for varB

you have to check your code and debug that which condition running continuously
One more explain me, what you want to do?

OK so I am trying to write a storygame for udemy academy… only I want to be deadly and make it a maths game so when you go to state.lvl1 I want it to say that Dude has [varA] brothers who are bringing [varB] guests to a party.
I could set the variables when I initialise the game but I want the numbers to change every time I come back to that lvl1 stage. So I want to be able to call the pickNumbers function and get a number between 3 and 7 for varA and the same for varB. At the moment it runs fine - no errors but the variable numbers just cascade as they are being called every frame. How can I call the function just once when I reach that state?

Hey I think I worked it out with a Boolean, set it to false - inside the pickNumbers function I say if its false pick the numbers and then set it to true!
Cheers:)

1 Like
 public int varA;
    public int varB;

    public static bool callToPick = true;

    public void PickNumbers()
    {
        varA = Random.Range(3, 8);
        varB = Random.Range(3, 8);
    }
    void Update()
    {
        if (callToPick == true)
        {
            PickNumbers();
            callToPick = false; // true this variable if you want to call again to PickNumbers() function
        }
    }

You are right…

Excellent! thanks for this:)

1 Like