Sound on collisions

Im sorry that im posting this again… But i cant seem to find a way to get this right.'m probably missing something simple :/… I thought I had it right with the help I got last time I posted…

As it is, I have a simple cube set up to be destroyed on Collision with a particle effect as the explosion, but I cant for the life of me get sound to play on the collision… Thank you in advance for the help.

Here is the code Im using:

#pragma strict
var stars : ParticleEmitter;
var Sound : AudioClip;

function OnTriggerEnter (collision : Collider) {
	
	if (collision.gameObject.name == "Player")
	{
	Instantiate(stars, transform.position, transform.rotation);
	
	audio.PlayOneShot(Sound);
	
	Destroy(gameObject);
	
		}
	}

As a sound is an audioclip played by an audiosource, and as audiosource is a component which, like all components, only leaves as long as it’s gameobject, your sound is destroyed as soon as it starts. You have two possibilities :

  • Create an empty game object (new GameObject(…)) add an AudioSource, give the audioclip ref and tell it to play. Use Destroy( thatNewGO, Sound.Length ) to destroy the gameobject once the sound is played. By the way, you could also do that for the initial gameobject, but I guess you have other script that you don’t want anymore, renderers and stuff.
  • Attach the sound to the particle system’s game object and make sure it plays on awake.