Adding sound to coins and death

Hey guys! So I’m working on a project and I needed to play sounds while collecting items and dying on my mini game, but I simply cannot make that work! I tried using many many types of scripts, but nothing seems to really work for me…

You may notice the scripts are pretty much the same, I simply changed the player tag to ‘‘PickupTrigger’’ and the coins and enemies are untagged, but I suppose this is not the best way to do it, but I have no knowledge whatsoever on C#

This is the script for collecting an item:

```csharp
**using UnityEngine;

using System.Collections;

public class Pick : MonoBehaviour

{

    void OnTriggerEnter2D(Collider2D c)

    {

      if (!c.gameObject.tag.Equals("PickupTrigger")) ;

      {

       Destroy(c.gameObject);

       }

   }

}

And this is the script for the enemy to kill me:

[code=CSharp]using UnityEngine;

using System.Collections;

public class KillPlayer : MonoBehaviour

{

void OnTriggerEnter2D(Collider2D c)

   {

    if (!c.gameObject.tag.Equals("PickupTrigger")) ;

    {

      Destroy(c.gameObject);

    }

 }

}

[/B]**
```

Hi,

Your code does not have anything related to Play an AudioClip

First attach an AudioSource to your gameobject (your player should have a collider with IsTrigger checked to enable OnTriggerEnter2D). It does not need to have a tag. But you need to assign tags to coins and enemies. Let say “Coins” and “Enemies”

Your Script should be something like this;

//Drag drop your 2 audio files inside into below array in the Editor
public AudioClip[] sounds;

    void Start ()
    {
        myaudiosource = GetComponent<AudioSource>();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag.Equals("Coins"))
        {
          myaudiosource.PlayOneShot(sounds[0]);
        }
        else if(collision.gameObject.tag.Equals("Enemies"))
        {
          myaudiosource.PlayOneShot(sounds[1]);
        }
    }
1 Like