Collision with same gameobject only once


I’m making a pool (snooker) game. Each ball has a script attached on it named “Ball”

This script has OnCollisionEnter() function, and it just plays a (HIT) sound whenever it hits another ball (having same script attached).

So, when two balls collide, they play the sound two times of course. I want the sound to be played once.

Here’s the code,

void OnCollisionEnter (Collision Other) {
	if (Other.transform.tag.Contains ("Ball")) {
		Debug.Log ("Ball Hit");
		HitBallAS.Play ();

you can create a public variable for a ball to temporarily store the last colliding ball.

public class Ball : MonoBehaviour
        /// <summary>
        /// Temporarily hold the reference to the justt collided ball
        /// </summary>
        public Ball justCollidedWith;

        private void OnCollisionEnter(Collision collision)
            // Get the ball I am colliding now
            var otherBall = collision.gameObject.GetComponentInParent<Ball>();
            if (otherBall == null) return;

            // if this ball is one I have just collided, do nothing
            if (otherBall == justCollidedWith)
                // important is to clear the last collided reference to be able to skip colliding only ONCE
                justCollidedWith = null;

            // set the last collided ball to the other Ball so it can skip me the next time ONCE
            otherBall.justCollidedWith = this;

            //do something else


public class AudioMgr : MonoBehaviour {
    public AudioSource source;
    public static AudioMgr Instance;
    private void Awake()
        Instance = this;

    public void PlayAudioClip()
        if (source.isPlaying) return;