- Home /
2D platformer: how do we make ammo boxes respawn after a certain amount of time after pickup?
Hi guys
I'm working on a small multiplayer game where the players need to shoot each other. There's a cap on their ammo, but they can get full ammo if they collide with our ammo gameObject. The problem here is that the ammo box is gone forever when collision occurs. How do we make it respawn after 20 seconds on the same location? Scripting in C#
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Ammo")
{
if (currentAmmo != maxAmmo)
{
currentAmmo = maxAmmo;
ammoSound.Play();
Destroy(other.gameObject);
}
}
}
$$anonymous$$aybe it's not a good idea destroying the gameobject but hiding it for those 20 seconds ins$$anonymous$$d? And when the 20 seconds have passed, it gets visible once again. Thoughts on this? And what would I need to do to make this happen?
Answer by goutham12 · Dec 04, 2019 at 01:11 PM
IEnumerator SpawnAmmo(int timeGap)
{
while(timeGap > 0)
{
yield return new WaitForSeconds(1);
timeGap -= 1;
}
//SpawnAmmo();
}
Now in your OnTriggerEnter
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Ammo")
{
if (currentAmmo != maxAmmo)
{
currentAmmo = maxAmmo;
ammoSound.Play();
Destroy(other.gameObject);
StartCoroutine(SpawnAmmo());
}
}
}
Hello. Thanks for answering. I inserted this, however there's a red line underneath SpawnAmmo when starting the coroutine in the OnTriggerEnter2D function. I don't understand why as I wrote the exact same name in the IEnumerator.
$$anonymous$$y console says: There is no argument given that corresponds to the required formal parameter 'timeGap' of 'P1Controller.SpawnAmmo(int)'
Change the StartCoroutine to StartCoroutine(SpawnAmmo(20)); to spawn in 20 seconds.
The routine, as written is expecting an int to be passed to it, to tell it how many seconds to delay.
Hope this helps, -Larry
Answer by mrlekova · Dec 04, 2019 at 01:24 PM
It should be noted that I have several conditional statements within the OnTriggerEnter2D function such as colliding with monsters and picking up health (which also needs to respawn after some time).
I don't understand in which line you got the error. If you got error in the line Startcoroutine(SpawnAmmo())... Then check your namespaspases Did contains line
Using system.collections
Your answer
![](https://koobas.hobune.stream/wayback/20220612215700im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to setup health, respawn/checkpoint, lives systems 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Add audio. 1 Answer
HOLD THE JUMP BUTTON TO JUMP HIGHER 0 Answers