Reputation: 3
Good day,
I'm new to coding so bear with me. I have a coroutine which I want to call so I have a delay to my respawn. however, it's doing everything but the delay. Unity C# :)
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Destroy(gameObject);
StartCoroutine(Reset());
}
}
IEnumerator Reset()
{
yield return new WaitForSeconds(4);
LevelManager.instance.Respawn();
}
}
Upvotes: 0
Views: 1105
Reputation: 16
As Mohamed pointed out, executing gameobject is destroyed before WaitForSeconds properly triggered at the end of the frame, and therefore your code does not reach LevelManager.instance.Respawn(). Would it disturb rest of your flow if destroy is executed after Respawn() like this?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
StartCoroutine(Reset());
}
}
IEnumerator Reset()
{
yield return new WaitForSeconds(4);
LevelManager.instance.Respawn();
Destroy(gameObject);
}
}
Upvotes: 0
Reputation: 640
it's very simple, the object is already destroyed so what(Script) after Destroy(gameObject);
on the next frame
will not work, as I told you in the comments the set a log message on IEnumerator
to check it out.
to understand how it works: Check this Script
void Awake() // the First Call // all lines inside Awake is Called
{
Destroy(gameObject); // Object is now Destroyed
print(1); // on the Same Frame Call // Printed
StartCoroutine(Reset()); // Called
}
IEnumerator Reset()
{
print(2); // will printed ... Called and on the same frame
yield return new WaitForSeconds(1); // Called but will be destroyed in the next frame
print(3); // not printed ..
}
private void Start() // Start will be called after the Awake calls are finished and the object still exists and is active so it will not be Called
{
print(4); // not printed ..
}
Upvotes: 3