Destroy gameobject and then play sound.

Hey

I want to pick up a coin, and then play a sound.

But as it is right now, i playes the sound and then destroys the coin.
Is there any way to destroy the coin and play the sound at same time, so that the coin disapear immediatly and the sound starts when the coin disapears and plays until it’s finished

#pragma strict

var coinValue : float;
var MoneySound : AudioClip;

function Start () {
	if (Application.loadedLevelName == "Stibro")
	{
		coinValue = 1;
	}
	
	else if (Application.loadedLevelName == "Musik - og Teaterhus")
	{
		coinValue = 2;
	}
	
	else if (Application.loadedLevelName == "Odense Havn")
	{
		coinValue = 5;
	}
	
	else if (Application.loadedLevelName == "Letbane")
	{
		coinValue = 10;
	}
	
	else if (Application.loadedLevelName == "Nyt OUH")
	{
		coinValue = 10;
	}
}

function OnTriggerEnter (info : Collider){
	if (info.tag == "Player")
	{
		if (GameObject.FindGameObjectWithTag("Coin")){

		GameMaster.currentScore += coinValue;
		Destroy(gameObject);
		
	 	audio.pitch = 0.85;
		audio.clip = MoneySound;
		audio.Play();
		yield WaitForSeconds (audio.clip.length);
		}
	}
}

Look into PlayClipAtPoint

I know that, but I have like 2500 coins that I have to make a PlayClipAtPoint on :slight_smile:
Thought there were an easier way :wink:

Play the sound on the player instead of on the coin. Also - you only have to edit a script once so the number of instances you have is irrelevant. (Unless you have a separate script on every coin in which case…don’t do that :slight_smile: )

Yeah, I’m not seeing how the number of coins you have is relevant to using PlayClipAtPoint?

Another way is to disable the renderer while the audio plays and destroy it when it’s done.

function OnTriggerEnter (info : Collider){
    if (info.tag == "Player"){
        if (GameObject.FindGameObjectWithTag("Coin")){
            GameMaster.currentScore += coinValue;
            renderer.enabled = false;//Destroy(gameObject);
            audio.pitch = 0.85;
            audio.clip = MoneySound;
            audio.Play();
            yield WaitForSeconds (audio.clip.length);
            Destroy(gameObject);
            //Or remove yield and use Destroy(gameObject, audio.clip.length)
        }
    }
}

Or you could use Unity - Scripting API: AudioSource.PlayOneShot .

Don’t know if these objects are enable and disabled but OnDisable is called on destroy. Even if you do enable and disable it you could add a boolean to determine if the object was picked up by the player or not.