WaitForSeconds not working in custom function

Hello, everyone. I have this explosion script that I wrote, but It is destroying the object before the object can play the sound. I put in `yield WaitForSeconds(sound.length);` but it still doesn't work. Any help would be appreciated. Here is my code:

@script RequireComponent(AudioSource);

var explosionRadius : float;
var damage : int;
var power : int;
var particleEffect : GameObject;
var sound : AudioClip;
var lifeTime : float;
private var audioSource : AudioSource;

function Awake()
{
    audioSource = gameObject.GetComponent(AudioSource);
    Destroy(gameObject, lifeTime);
}
function OnCollisionEnter(col : Collision)
{
    if(col.gameObject.tag != "Enemy")
        Explode();
}
function OnTriggerEnter(col : Collider)
{
    if(col.gameObject.tag != "Enemy")
        Explode();
}
function Explode () 
{
    if(sound != null)
    {
        audioSource.PlayOneShot(sound);
    }
    var explosionPosition : Vector3 = transform.position;
    var colliders : Collider[] = Physics.OverlapSphere (explosionPosition, explosionRadius);
    for(var hit in colliders)
    {
        hit.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
        if(hit.rigidbody)
        {
            hit.rigidbody.AddExplosionForce(power, explosionPosition, explosionRadius, power);
        }
    }
    if(particleEffect)
    {
        var go : GameObject = Instantiate(particleEffect, transform.position, transform.rotation);
    }
    yield WaitForSeconds(sound.length);

Destroy(gameObject);

}

2 Answers

2

try using AudioSource.PlayClipAtPoint() instead of audio.PlayOneShot(). It creates an audio source and then cleans it up when the sound is done playing. You won't need the yield in this case.

Here's the link in the scripting manual:

http://unity3d.com/support/documentation/ScriptReference/AudioSource.PlayClipAtPoint.html

I think your problem could be the variable lifeTime. Maybe it is set too short?

thanks, but that is just me being stupid and not getting rid of that var.