Destroy and play sound on collision

Hi there,

I’m making a game where you have to hit game objects, the problem is that no code is working for me…
I just want to destroy and play sound, does somebody know how do this?
This is my code for destroying a game object and for the audio I don’t know how to do that:

void DestroyGameObject()
{
Destroy(gameObject);
}

Hi @SamVorst

I saw you posting similar questions earlier… the things you have asked are (mostly) already explained in introductory tutorial videos and in manual or in API reference.

“the problem is that no code is working for me…”

You show barely anything and practically ask others to fill in the part you haven’t even started yet. I see no audio related code, so did you google for this? :slight_smile:

If you had googled for this issue, you would know, that you will get solutions from Unity Answers, YouTube videos and from manual / API page links.

Just put Unity + your question to google and you’ll see.

It is not that I don’t want to help, but you should learn to help yourself if you want to get something done with code. There is no way around needing to search for all kinds of solutions, you’ll have to do that all the time.

You already know the steps, just google each step and combine those. Then see if you still can’t get it done.

1 Like

I’l try!

@SamVorst

Things you’ll need:

  • Collision event methods (either for 2d or 3D, depending on which physics system you use).
  • Audio source
  • Audio clip for that source to play
  • Play audio clip from source when object gets destroyed
  • Note - you’ll have to create a separate GameObject for the audio source if you want to destroy your GameObject before the sound ends.

thanks!

hi to all

since all gameobjects destroying automatically before loading new scene
for me better work SetActive (true) and SetActive (false)

public GameObject yourscenegameobject;


void Update() {
      
        //for better compatibility with others platforms
        #if UNITY_ANDROID
        if ()

        {  
            yourscenegameobject.SetActive (true);
        }

        #endif

        else
        {
            yourscenegameobject.SetActive (false);          
        }

    }

sure if you you have a big game project with a lot of gameobjects on the scene where that`s really needed

try doing like this

    void destroygameobjectonyourscene()
    {
        gameObject.tag = "tag your gameobject";

        //destroying gameobject after 5 second
        Destroy(gameObject, 5);
    }





     void OnCollisionEnter2D(Collision2D other)
    {

        #if UNITY_ANDROID
        if (other.gameObject.tag == "tag your gameobject")
        {       
            destroygameobjectonyourscene();
        }

    else   {
    }

}

If you have some problems with destroying object on the scene and always see messages on console
can`t destroy gameobject because this gameobject allready destroying or something else like this,
just enable or disable your gameobjects on the scene through SetActive (true) and SetActive (false)

Well if you want to destroy your object, then do so after the sound has played. You can delay the Destroy() like this:

audioSource.PlayOneShot("YourClipHere"); // Assuming your clip is 0.5 seconds long
Destroy(gameObject, 0.6f); // Delay destroy 0.6th of a second

Now you can access your game objects sprite renderer and collider and set its activeness to false so it looks destroyed to the player.

audioSource.PlayOneShot("YourClipHere"); // Assuming your clip is 0.5 seconds long

gameObject.GetComponent<SpriteRenderer>().enabled = false;
gameObject.GetComponent<Collider2D>().enabled = false;

Destroy(gameObject, 0.6f); // Delay destroy 0.6th of a second

One last method worth mentioning is:

PlayClipAtPoint('YourClipHere", gameObject.transform.position, 1.0f);

// Enter your audioclip, Vector3 coordinates,and volume
// This creates an audioSource at that location, plays the clip,
// and you can custom set the volume. Pretty cool, right? :)

The Audio Source is destroyed when the clip finishes.

4 Likes

Thanks! But with no succes because i got the error cannot convert from ‘string’ to ‘UnityEngine.AudioClip’.

I had a earlier project where I used this code but with no succes too, does someone know what i’m doing wrong?

    #region Unity Editor Fields
    [SerializeField] private int _coinValue = 1;
    [SerializeField] private AudioSource _as;
    [SerializeField] private AudioClip _coinSound;
    #endregion
    #region Fields

    #endregion
    void Awake()
    {
     
    }

    // Start is called before the first frame update
    void Start()
    {
     
    }

    // Update is called once per frame
    void Update()
    {
     
    }

    private void OnTriggerEnter (Collider target)
    {
        if (target.gameObject.tag == "player")
        {
            //inactive coin
            CoinOnTrigger();
        }
        print("I collide");
    }

    private void CoinOnTrigger ()
    {
        //Play the sound on trigger only
        _as.PlayOneShot(_coinSound);
        gameObject.SetActive(false);
    }
}

Thanks Sam

Is this the exact error message? If not, please copy the entire error in your console or screen shot it.

yup, this is it:
Assets\Scripts\RedEnemy.cs(11,33): error CS1503: Argument 1: cannot convert from ‘string’ to ‘UnityEngine.AudioClip’

this is my code.

 using UnityEngine;
using System.Collections;

public class RedEnemy : MonoBehaviour
{
    void Start()
    {
        AudioSource.PlayOneShot("explosion"); // Assuming your clip is 0.5 seconds long

        gameObject.GetComponent<SpriteRenderer>().enabled = false;
        gameObject.GetComponent<Collider2D>().enabled = false;

        Destroy(gameObject, 0.6f); // Delay destroy 0.6th of a second

    }

    void Update ()
    {

    }
}

I finally got it!!!

1 Like

Is the script provided above your RedEnemy Script? If so, then what is on line 11? That’s where you’re getting your error from but I don’t see anything there.

I didn’t see you posted this until after I just posted. My fault :slight_smile:
Care to share your solution in case it may help another?

I found it! but see nothing too.

Thanks, you helped me a lot!

1 Like
 using UnityEngine;
using System.Collections;

public class RedEnemy : MonoBehaviour
{

    [SerializeField] private AudioSource _as;
    [SerializeField] private AudioClip _explosionSound;

    void Start()
    {

    }

    void Update()
    {

    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "player")
        {

            Destroy(gameObject);

            _as.PlayOneShot(_explosionSound);
        }
    }
}

Was it because you were using OnTriggerEnter() instead of OnCollisionEnter()?

I think so.

1 Like

Please do not post answers like these cus I am also looking for a solution for a similar problem and it is annoying to see such answers since they are not helpful but more like scolding. Either write an actual helpful answer or dont write anything. I dont think you can teach a life lesson to a stranger on a unity forum.

2 Likes