Time to Drop Dropper Not Following Variable Time

Hi, I’m currently trying to use the Random.Range method to generate a random number that will tell the dropper to turn on gravity, render, and then drop.

I’m able to verify that the random number is generated and instantiated through my variable num through Debug.Log. When I use it in my if statement “if (Time.time > num)” instead of a SerializedField, I find that my dropper ignores the Randomly generated time and drops instantly.

How can I make it so that it follows the time created with Random?

public class Dropper : MonoBehaviour

{

MeshRenderer renderer;

Rigidbody rigidBody;

int num;

// Update is called once per frame

void Start()

{

    renderer = GetComponent<MeshRenderer>();

    rigidBody = GetComponent<Rigidbody>();

    renderer.enabled = false;

    rigidBody.useGravity = false;

    int num = Random.Range(3, 10);

}

void Update()

{

    Timer(num);

}

void Timer(int num)

{

    if (Time.time > num)

    {

        rigidBody.useGravity = true;

        renderer.enabled = true;

    }

}

}

Thanks!

Hi coldoo,

Welcome to our community! :slight_smile:

I’ve just skimmed your code, and it looks good apart from a little detail. I’m not telling you the solution right away because there is a mistake in your code from which you’ll learn a lot about programming in C#.

And here is the relevant information: We can declare local variables and instance variables. Instance variables are at the top of our class. Local variables are declared within methods.

What is the syntax for declaring a variable? If you know that and read your code carefully, you’ll very likely spot the little mistake. Hint: The mistake consists of three characters. Remove them, save your script, and test your game again.

Please let me know if you spotted the problem and fixed it. :slight_smile:


See also:

@Nina,

Thanks for the welcome!

I was able to find the mistake. Thanks very much for the help :slight_smile:

I should start just waiting a day and coming back with fresh eyes so I can find silly mistakes like that :sweat_smile:

Hehe, that’s true. Mistakes like that are very, very common, even among professional programmers. The compiler does not complain because the code itself is valid. That makes those problems difficult to spot.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms