audio.Play() and Destroy (gameObject) timing issue in Unity

5.5k views Asked by At

I've done script for my star to give 1 score point, make particle, play a sound and destroy object. Everything is working fine but now script waits until sound stop playing. What method would you suggest to destroy object before playing sound? I can make new gameobject audiosource prefab, attach it to star's group and call playback of it like I did with particle system or is there better way to do that?

using UnityEngine;
using System.Collections;


public class Star : MonoBehaviour {

    public ParticleSystem StarParticle;

    public AudioClip otherClip;

    IEnumerator OnTriggerEnter (Collider player)
    { 
        ScoreManager.score += 1;


        StarParticle.Play ();

        AudioSource audio = GetComponent<AudioSource>();
        audio.Play();
        yield return new WaitForSeconds(audio.clip.length);

        Destroy (gameObject);

    }
}

That's the code.

2

There are 2 answers

6
Martin On

From reading the comments, how about this:

Take the value of audio.clip.length into a variable and reduce it, such as divide by 2 or by 4, etc, so that the script will continue 50% or 25% through the audio file play.

 IEnumerator OnTriggerEnter (Collider player)
{ 
    ScoreManager.score += 1;


    StarParticle.Play ();

    AudioSource audio = GetComponent<AudioSource>();

    waitValue = (audio.clip.length/2);
    audio.Play();
    yield return new WaitForSeconds(waitValue);

    Destroy (gameObject);

    }
0
Phantoms On

That's solution of my problem. I disable collider (to not allow other ppl to get points from that star) and mesh (to make star invisible) and then after playback I destroy my star gameObject. Thx for replies!

using UnityEngine; using System.Collections;

public class Star : MonoBehaviour {

public ParticleSystem StarParticle;

IEnumerator OnTriggerEnter (Collider player)
{ 
    ScoreManager.score += 1;


    StarParticle.Play ();

    AudioSource audio = GetComponent<AudioSource>();
    audio.Play();
    GetComponent<Collider>().enabled = false;
    GetComponent<MeshRenderer>().enabled = false;
    yield return new WaitForSeconds(audio.clip.length);

    Destroy (gameObject);

}

}