Destroying Collected Objects / Playing Audio

Hi guys,

I've got some pickups in my game that you collect by colliding with them. They are then destroyed and a number is added to your objects counter. Here is (some of) the code I have written:

else if(hit.gameObject.tag == "Helmet1")
    {

        audio.PlayOneShot(pickup);

        Destroy(hit.gameObject);
        OBJECTNUMBER += 1;
        g_Helmet.animation.Play("g_Inv_HelmetAnimation2");
        print("you now have" + OBJECTNUMBER);

    }

}

Now. This works fine, but what happens is because the audio source is set to the object, and then the object gets destroyed, the sound doesn't play. So to combat this, I put in a yield here:

else if(hit.gameObject.tag == "Helmet1")
    {

        audio.PlayOneShot(pickup);
yield(1);
        Destroy(hit.gameObject);
        OBJECTNUMBER += 1;
        g_Helmet.animation.Play("g_Inv_HelmetAnimation2");
        print("you now have" + OBJECTNUMBER);

    }

}  

This enabled the sound to play before the object was destroyed - but - now sometimes the OBJECTNUMBER goes up by two or three, because I am still colliding with the object.

How can I write the code so that it only goes up by 1, and the pickup sound can play?

Thanks!

You could add the sound to the camera or any game object that wouldn't be destroyed. Just add this to the top of the script:

var soundObj : GameObject;

then use soundObj.audio.PlayOneShot(pickup);

with this you can use the first script and get rid of yield.

+1 - I dont get a click sound with Play On Awake on.

C# Solution:
GameObject>Create Empty>Name it something (I named it Engine)
Select the Gameobject in the Hierarchy
Component>Add Component>Audio>Audio Source

Enemy.cs

private GameObject engine;

void Start () {
     direction=Direction.UP;
     engine=GameObject.Find ("Engine");
}
        
        
public void TakeDamage(int amt){
     hp-=amt;
     if(hp<=0){
          engine.audio.PlayOneShot (deathSound);
          Destroy(gameObject);
     }
}