- Home /
Using coroutines to pause the game
I'm trying to make a particlesystem appear upon a collision and make it disappear after three seconds. Can I accomplish this using coroutines? The code I have so far (which doesn't work) is: using UnityEngine; using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public ParticleSystem ps;
private float amt = 3f;
// Use this for initialization
void Start () {
ps.renderer.enabled = false;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter (Collider other) {
Destroy(this.gameObject);
ps.transform.position= new Vector3(this.transform.position.x,this.transform.position.y, this.transform.position.z);
ps.renderer.enabled = true;
StartCoroutine(pauser());
}
IEnumerator pauser()
{
yield return new WaitForSeconds(amt);
Destroy(ps.gameObject);
}
}
Answer by fafase · Jun 28, 2012 at 04:55 AM
In your trigger function, you destroy the object first, so anything coming after won't do.
Additionally it doesn't matter if you call Destroy before or after starting the coroutine. Destroy is delayed until the end of the current frame. The real problem is that the coroutine runs on this object. When you destroy it, the coroutine will be destroyed as well. You need either an script on another object on which the coroutine can run, or don't destroy this object. You can just disable the renderer so it's not visible anymore. You can destroy it when your coroutine has finished.
I fixed it to make it disappear, and it's working fine. Why is it, though, that it executes the ps.renderer.enabled= true, which is after the destruction of the object?
Thanks for pointing that out. I'll leave that there so it won't look like your talking to yourself...