- Home /
Collision with same gameobject only once
Hi
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 ();
}
}
Answer by YiYiBaBa · Mar 12, 2019 at 02:52 PM
easy
public class AudioMgr : MonoBehaviour {
public AudioSource source;
public static AudioMgr Instance;
private void Awake()
{
Instance = this;
}
public void PlayAudioClip()
{
if (source.isPlaying) return;
source.Play();
}
}
Answer by misher · Mar 12, 2019 at 11:27 AM
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;
return;
}
// set the last collided ball to the other Ball so it can skip me the next time ONCE
otherBall.justCollidedWith = this;
//do something else
}
}
Your answer
Follow this Question
Related Questions
How can I make a sound deploy after colliding with a certain object (or terrain)? 1 Answer
sound controlled objects? 1 Answer
play animation when thrown object collides 1 Answer
How would I implement this game mechanic? 0 Answers
instantiate object only once in current position and than again in another 0 Answers