destroy object and play sound?

So, I’m able to either destroy the object or play the sound when collision is detected. I can’t seem to figure out what I can do to get both. Currently the script just plays the sound when hit, and doesn’t destroy the game object. I’m hoping someone could point me in the right direction? This seems to be something simple but I can’t seem figure out the approach I need to take.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class DestroyShipAfterHit : MonoBehaviour

{
public GameObject other1; // this is manually placed
public GameObject other2;

void OnCollisionEnter2D()

{
    if (gameObject.name == "Ship")  // if the objects touch 

    {
        AudioSource audio = GetComponent<AudioSource>(); 

        audio.Play();  // plays sound when collided.

        Destroy(other1);  // destroy ship
        
    }

}

}

1 Like

Your problem is very simple :

You play the sound using an audio source, and you destroy the object holding the audio source.

You have multiple solutions :

  • Do not destroy the object, just disable it and destroy it after a certain delay

  • Create a global object holding an audio source you will use to play the destroy sound

  • Before destroying the object, Instantiate an empty gameObject, attach an audio source and make it play the sound. Major drawback here : many empties may be created, which will slow down your game.

  • Use AudioSource.PlayClipAtPoint static function. This function creates an audio source but automatically disposes of it once the clip has finished playing.

On your OnCollisionEnter, try putting the word Collision2D in those parenthesis.
Also try putting .gameObject after the other1.
Could be that the object get destroyed before it plays the sound.
Try putting the GetComponent audio source into the awake function;

void OnCollisionEnter2D (Collision2D Col) {

if (Col.gameObject.name == "Ship") {

audio.Play ("theSound");

Destroy (other1.gameObject);

}

}

You cannot delete other1 because it’s probably not a reference to a gameobject

Change

Destroy(other1);  // destroy ship

to

Destroy(other1.gameobject); // destroy ship

And for the audio, I find that doing this works better :

public AudioClip audio;
AudioSource.PlayClipAtPoint(audio, this.gameObject.transform.position);

Hello,

I am working on a Bubble Popping Game for Android and had to find the answer to this question via a C# tutor.

Here is a step by step Guide on how to play a sound file & destroy an object or prefab:

1.) Find the sound you want to use in your File Explorer and drag it into your Unity Assests Folder in the Project View. (TIP: You may download Audacity for free and trim the audio clip prior to importing it to Unity.)
2.) On the game object you wish to have the sound play on (or prefab you wish to play the sound on) selected in Hierarchy, you want to open the Inspector tab and Add Component > Audio > Audio Source.
3.) Now, with your object selected in Hierarchy look in the Inspector under the Audio Source component you added in the previous step, click the little circle and select the sound file you imported in step 1.
4.) Be sure to Uncheck Play On Awake.
5.) Right Click on your Assets Folder in the Project View > Create > C# Script and name it whatever you want.
6.) Cut and paste the following code:

using UnityEngine;

public class YourScriptNameHere : MonoBehavior
{
    public Renderer rend;

    public void Start()
    {
        rend = GetComponent<Renderer>();
        rend.enabled = true;
    }

    public void YourMethodNameHere()
    {
        AudioSource audio = GetComponent<AudioSource>();
        audio.Play();
        rend.enabled = false;
        Destroy(gameObject, audio.clip.length);
    }
}

+7.) Save the Script & Attach it to your object. Locate the script in your Assets Folder. First, Click on the Object in the Hierarchy. Then drag your Script onto the selected Object.

+8.) There is no call to this method currently. Assuming you already created an Input Method you would just need to add the call for this method. EXAMPLE: YourMethodNameHere(); should be placed inside your call method.

IF NOT, Continue reading…

Creating a CALL for the method:
This is for Touch Input using an Android.

1.) Lets create a new C# Script and name it “BubbleBehavior”.
2.) Copy & Paste the Above Code into this new C# Script.
3.) Change YourScriptNameHere to BubbleBehavior AND Change YourMethodNameHere() to TouchPop() +NOW SAVE THE SCRIPT & ATTACH IT TO YOUR OBJECT
5.) Create another C# Script and name it “TouchDestroyer”.
6.) Copy & Paste the following code into TouchDestoryer.cs

using UnityEngine;

public class TouchDestroyer : MonoBehaviour 
{
	void Update ()
	{
		foreach (Touch touch in Input.touches) 
			{ 
				if (touch.phase == TouchPhase.Began) 
				{ 
					Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
					RaycastHit hit;
					if (Physics.Raycast (ray, out hit, Mathf.Infinity)) 
					{ 
						BubbleBehavior bb = hit.transform.gameObject.GetComponent<BubbleBehavior> ();
						if(bb != null)
						{
							bb.TouchPop ();
						}
					}
				}
			}
	}
}

Finally, Drag the TouchDestroyer script onto your Main Camera in the Hierarchy View.

Now you should be able to tap, play audio, disable renderer, and destroy your game object. In short, you can now play a sound when your object is destroyed.

I hope this helps!

Best regards,
Derek Rieger

I tried all of that and now it doesn’t do either. I’m getting an error when I’m trying to get it to play the sound.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class DestroyShipAfterHit : MonoBehaviour

{

void Awake()
{
    AudioSource audio = GetComponent<AudioSource>();

}

public GameObject other1; // this is manually placed
public GameObject other2;

void OnCollisionEnter2D(Collision2D Col)

{
    if (Col.gameObject.name == "Ship")  // if the objects touch 

    {

        audio.Play();  // plays sound when collided.

        Destroy(other1.gameObject);  // destroy ship
        
    }

}

}

Maybe AudioSource.PlayClipAtPoint can help?

void OnCollisionEnter2D(Collision other)
{
    if (gameObject.name == "Ship")  // if the objects touch 
    {
        AudioSource audio = GameObject.Find("Other").GetComponent<AudioSource>();
        AudioSource.PlayClipAtPoint(_audioSource.clip, transform.position); // plays sound on the collided position.
        Destroy(other);  // destroy ship

    }
}

Or how the Tanks demo does it, make a prefab of a gameobject that contains your particle VFX you want to play on creep death and also add to it a AudioSource. Then when your creep dies spawn this gameobject on the creep position and let it play the particles and sound you want and then kill it 1 second later. This way you are free to destroy as fast as you want to creep gameobject and still play the VFX and sounds.

@Jedd117 Or just use PlayOneShot instead? Seems a lot more straightforward than most of these answers.

In your example:

audio.PlayOneShot(audio.clip, 1f);

Audio.clip is obviously the clip stored in your Audio Source, and the float value in the overload is relative volume on a 0-1 scale, which defaults to 1f, I believe.

don’t know if this will help, but when my bullet collides with the enemy it explodes and a particaleffect is played. I attached the audio to the bullet, then the enemy, but as both were destroyed so was the sound, in the end it came to me to attach the audio to the partical effect and that worked for me. hope this is useful.