Play Audio on Collision or Trigger Enter

I have this code attached to my Object and I just want sound of this Object to play when it comes in collision with the Player.

For some reason the sound plays even when Player comes in contact with Enemy but neither one of those two have this audio file attached to it.

I also tried void OnCollisionEnter(Collision collision) but it didn’t help.

What am I doing wrong?

Thank you for any help.


void OnTriggerEnter(Collider gameObject)
{
	if (gameObject.tag == "player")
 {
	audio.Play();
 }
else audio.Stop();
}

You named the other object as gameObject, which is the name of a property - this may have confused the poor compiler’s brain and made it read the property gameObject instead of the variable you’ve created. Anyway, it’s a really bad idea to give the same name to different things, so I renamed the variable to otherObj. This code must be placed in the script attached to the same object as the audio source (NOT the player!):

void OnTriggerEnter(Collider otherObj)
{
    if (otherObj.tag == "player")
    {
        audio.Play();
    }
    else {
        audio.Stop();
    }
}

This will play the object’s sound when the object tagged “player” touches the trigger, and will stop when other object enters the trigger or the sound finishes (Play only plays continuously if loop is set!).
NOTE1: the tag available in Unity is “Player”, not “player” - make sure your tag is correctly spelled, or it will never work;
NOTE2: check if there’s some other instance of this script attached to the player - it could produce the problem you mentioned.

Problem here is that there is nothing to stop the sound from playing until something that is not a player enters your trigger! If it is a one-shot sound, you should use audio.PlayOneShot() instead of audio.Play (which instead sets the sound to play continuously)

Otherwise, you will need to keep track of which objects are in your collider (with a list of gameObjects) and have one sound associated with each gameObject which stops when that gameObject leaves - hardly the most straightforward of solutions!

I tried that but for some reason it won’t let me use PlayOneShot
This is the error I get which I dont understand. :frowning:

error CS1501: No overload for method PlayOneShot' takes 0’ arguments

I also thought of using:

IEnumerator Awake() 
{
   audio.Play();
   yield return new WaitForSeconds(audio.clip.length);
}

But I don’t how to make it work with my:
void OnTriggerEnter(Collider gameObject)

I found my problem.

I left one of those objects in my scene - after I deleted it everything works (for now).

Thank you for your help though those are good answers

Unfortunately I can check only one as correct.