x


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);
}
}
more ▼

asked Jun 28 '12 at 04:53 AM

Dave321 gravatar image

Dave321
2 1 2

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

In your trigger function, you destroy the object first, so anything coming after won't do.

more ▼

answered Jun 28 '12 at 04:55 AM

fafase gravatar image

fafase
10.5k 9 15 41

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.

Jun 28 '12 at 05:00 AM Bunny83

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?

Jun 28 '12 at 12:59 PM Dave321

@Bunny83 explained that in his comment.

Jun 28 '12 at 01:58 PM Wolfram

Thanks for pointing that out. I'll leave that there so it won't look like your talking to yourself...

Jun 29 '12 at 03:22 AM Dave321
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4167
x324

asked: Jun 28 '12 at 04:53 AM

Seen: 347 times

Last Updated: Jun 29 '12 at 03:22 AM