- Home /
OnCollisionEnter2D being called twice sometimes
I'm attempting to make a top-down racing game, but when my Player crosses the finish line it's calling collision twice henceforth adding 2 laps
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == 12)
{
Debug.Log("col enter " + gameObject);
lapCounter.AddToLapCount();
}
}
I found out through the debug log that when I don't turn while going through the finish it gets called once. When I do turn it gets called twice.
Answer by nicholasw1816 · Dec 02, 2018 at 02:22 AM
Try using a bool, it will ignore multiple collisions and only register the first. I would use ontrigger instead of oncollision as well.
public bool lapBool
void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 12 && lapBool == false)
{
//Set your bool to be true
lapBool = true;
}
}
void Update()
{
if (lapBool == true)
{
//Run your function
lapCounter.AddToLapCount();
lapBool = false;
}
}
I found this thread from a google search and I just want to say your solution put an end to my 5-day long bug hunting! I was really losing motivation, but this works a charm. THANK YOU!
Your answer
Follow this Question
Related Questions
Character controller collider? 0 Answers
Response speed in OnCollisionEnter / OnTriggerEnter 1 Answer
How to detect collision without OnCollisionEnter or OnTriggerEnter? 1 Answer
How to make multiple gameobjects instantiate from one collider? 3 Answers
How do I use an enemy's OnTriggerEnter to collide with stationary player? 2 Answers