Hi guys, i’m new to unity and want to ask a basic question.
I want to make my chili object to spawn back to the random x position with time gap after reaching some y axis point but its not working.
The problem is my chili is keep falling and the spawnAgain
method not working
screenshot of a text editor
// paste your code here
Hi @KejuPilihan !
First off, I just want to share some links to resources that may provide more thorough answers & explanations than I’m about to provide here:
Now as for your specific code…
I believe the issue you’re hitting is that you’re never actually starting your “SpawnAgain” IEnumerator method as a Coroutine - instead you are simple calling SpawnAgain directly.
Probably the best way for you to call it would be to use:
StartCoroutine(SpawnAgain());
which will allow the 'yield" to actually wait for the random 1 to 5 seconds.
If you want more control, such as the ability to start multiple SpawnAgain() Coroutines at the same time, or to Stop specific running coroutines, you can do something more like:
private IEnumerator currentSpawnAgainCoroutine = null;
IEnumerator SpawnAgain()
{
// your code that was already in here
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.name == "GameOverTrigger")
{
if (currentSpawnAgainCoroutine != null) StopCoroutine(currentSpawnAgainCoroutine);
currentSpawnAgainCoroutine = SpawnAgain();
StartCoroutine(currentSpawnAgainCoroutine);
}
}
That will make sure you stop any already-running SpawnAgain() coroutine in the currentSpawnAgainCoroutine variable (if any) before running a new one - which is good for keeping your memory less leaky.