So I’m extra new to coding. I’m doing bonus features for the Unity Jr programmer second project, Food Fight. I want to limit how quickly I can instantiate my projectile and/or limit how many instantiated clones I can have at a time.
I want to really understand all this, so please explain like I’m an idiot. I wont be offended.
Not sure if it makes a difference, but I combined the MoveForward and Destroy scripts for both the food and animals like this:
public float timer;
public float speed;
void Update()
{
Destroy(gameObject, timer);
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}
So after 2 seconds the food projectile instantiations are off screen and destroy themselves. How do I prevent rapid fire projectiles? Thanks.
BONUS POINTS: Instantiating my projectiles moves my player backwards slightly. What do? Thanks.
Okay, so I solved both problems all by myself through some experimentation. If anyone see’s this, feel free to critique and teach me something new.
So I created an int and had it ++ in the update method, then debug.log each update. I counted the average amount of increases per second and found it was around 31 updates a second. So this is now my shot limiter:
void Update()
{
if(timer > 0)
{
timer--;
}
if (Input.GetKeyDown(KeyCode.Space) && timer < 5)
{
timer += 30;
Instantiate(projectile, transform.position, projectile.transform.rotation);
}
}
For the bonus points, I made the projectile a trigger and changed OnCollsionEnter(Collision collision)
to OnTriggerEnter(Collider collision). I don’t know why this worked because I don’t fully understand what these minor differences really mean, so feel free to comment.
EDIT NOTE: Both this post and my OP have a “timer” variable, but they’re different scripts and unrelated.
Good problem-solving and great to see you measuring things to learn what values work well.
But Unity has some better ways. If your computer is very fast or you add and remove debug.log calls, the updates will happen at a different rate. There is a variable called Time.deltaTime
which is the fraction of a second since the previous update; in your case it was probably somewhere close to 0.333, or 1/30, meaning about 30 frames per second. If you do your math using this variable, you will always get the same results regardless of the speed of the computer.
As for OnCollisionEnter vs OnTriggerEnter, look at the collider components: if one is marked as a Trigger, then the trigger functions are called instead.
2 Likes
Thanks for the reply. I’ve heard of delta time. How would I implement it in this case?
Every update (which runs each frame) you add Time.deltaTime (the last frame time) to your timer variable. This way the timer will count in seconds, and not frames, so the behaviour will be consistent on all hardware