C#: Making a timer

I am trying to make a timer and I have been pulling my hair out for several hours. I know why it’s doing what it’s doing, but no matter how I frame it, it still will not work. So here goes… I need loop to declare a random value and if the timer is less than or equal to random value, increment until it is equal. The loop keeps kicking out of itself before timer is equal to the random value. It increments once, only.

    float rand = Random.Range(1,8);
    float timer = 0;
    
    if(timer <= rand){
         ++timer;
         Debug.Log(timer);
         if(timer == rand) //do something;
    }
    
    Debug.Log("done");

Thanks ahead of time for any help.

*The lack of the “==” was just a typo on here.

Solved.

A little difficult to understand exactly what you’re wanting to do and where your loop actually is (is the snippet encapsulated in an actual loop or is this “looping” in your Update method or something?). All I see is an if statement on line 4.

Currently this snippet is declaring and initializing a float timer which is happening every iteration of the loop. You probably meant to initialize it once outside the loop. Also, on line 7 you aren’t comparing timer to rand, you are assigning rand to timer and checking the return value (which if non-zero should evaluate to true, otherwise false). The comparison operator is ‘==’, not ‘=’.

Maybe you meant something like this:

float rand = Random.Range(1,8);
float timer = 0;
     
while(timer < rand)
{
    ++timer;
    Debug.Log(timer);
    if(timer == rand)
    {
        //do something
    }
}
     
Debug.Log("done");