Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[Solved]Avoid multiple objects triggering collision during same frame

Discussion in 'Scripting' started by Shack_Man, Dec 18, 2018.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    367
    EDIT:
    Not sure if there actually were multiple collisions, been a long day. but using bools on both objects to double check gives me the results I wanted: No matter how many objects A bump into how many objects B, only one of each can connect.


    OLD QUESTION:

    I have an object A which is supposed to call an event when it hits object B, and I only want that function to run once. The problem is when multiple objects B hit object A in the same frame. Using a bool or switching layers thus becomes useless. To complicate the matter I have a lot of objects A and B.
    I tried using a simple timer.


    Code (CSharp):
    1. private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.  
    4.         collisionDelay = 0.1f;
    5.      
    6.            //layer 8 does not collide with anything else
    7.             gameObject.layer = 8;    
    8.    
    9.     }
    10.  
    11.     private void Update()
    12.     {
    13.         if (collisionDelay > 0)
    14.         {
    15.             collisionDelay -= Time.deltaTime;
    16.             if(collisionDelay <= 0)
    17.             {
    18.                  DoAwesomeStuffButOnlyOnce();
    19.  
    20.             }
    21.         }
    22.     }
    23.  

    It is however an unclean solution and doesn't lead to perfect results. Any better ideas?
     
    Last edited: Dec 18, 2018
  2. Klimka13

    Klimka13

    Joined:
    Jul 30, 2019
    Posts:
    3
    Thanks for sharing this.
    After many hours of searching and debugging – it worked for me too!