- Home /
Pausing/Waiting/Stopping code in a 2D Collision Function
Hi, I am making a 2D game and I am having a problem with this script:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class TheRestarter : MonoBehaviour {
private Animator anim;
public string GameOverScene;
void Awake () {
anim = GetComponent<Animator> ();
}
void OnCollisionEnter2D(Collision2D target)
{
if(target.gameObject.tag == "Enemy")
{
anim.Play ("RedGiantDeath");
SceneManager.LoadScene(GameOverScene);
}
}
}
I want to pause the time in-between the anim.play line and the scene manager load scene line. I can't pause code without having an IEnumerator function. But for 2d Collision I have to do the On Collision enter function. Can someone please help me.
Comment
Best Answer
Answer by wojtask12 · Jun 11, 2016 at 09:50 PM
You should use coroutine from inside OnCollisionEnter2D. I'd look something like:
void OnCollisionEnter2D(Collision2D target)
{
if(target.gameObject.tag == "Enemy")
{
anim.Play ("RedGiantDeath");
StartCoroutine(DelayedSceneLoad());
}
}
Ienumerator DelayedSceneLoad()
{
yield return new WaitForSeconds(5);
SceneManager.LoadScene(GameOverScene);
}