Making sound playing once after collision with another object... how :( ?

Hi guys!

I have little trouble…
I searched similar problems, but with no results. I want to make simply thing. How to make a script, that will be play a sound (audio source) only once when the Player object get trigger enter collision with the object with audio source? Everything i have is in 3D scene in Unity, i have a basic player object as a capsule mesh with capsule collider (ofcourse with “Is Trigger” option ‘on’) and another object Keys (which is just a box/cube mesh) and with box collider (“Is Trigger option OFF”). I made simply script (attached to that Keys object) like:

void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.CompareTag("Player"))
        //if (GetComponent<Collider>())
        {
            GetComponent<AudioSource>().Play();
            Debug.Log("collision");
            //return;
        }
    }

And now it works weird - when I collide with the Keys object the sound is played many times when Im overlapping the Keys object. And I made debug log ‘collision’ to check the collisions and these are instantiating in console with no ending as a loop. Also, when I collide second time with the box - the sound starts playing in Trigger Exit… although I used ‘On Trigger Enter’ method…

So, there is any solution how to fix that, and make the method, to play the sound once when OnTrigger Enter, and than play only when the collision happens again (after leaving the box by player) ?

Pls help!

That’s strange behavior. Do you have a NavMeshAgent on your object? (Thinking it might be a case of this.)

Why is it strange behavior :smile: ? I want to indicate the stepping on the keys with single sound, without doubling effect…
I haven’t got NavMeshAgent (I tested with that component, and its not solving the problem).

Because OnTriggerEnter is only supposed to fire once. If in your project it’s firing on every frame while the objects are colliding, that’s strange.

Is the code above all the code affecting these objects in your project? Are you sure you don’t have something adjusting the colliders, enabling/disabling objects, etc.? Those things can force the physics engine to recalculate collisions, which would make OnTriggerEnter fire again.

Ok, I tried player controller from Standard Assets of Unity, and now its working great - as i wanted. So I don’t know what I made wrong with my player object… :wink: So I will be working with this Player Controller object (which is more expanded and complex by the way) from standard assets.
Thanks for help! :wink: