Search Unity

Multiple GOs in OnCollisionStay2D (C#)

Discussion in 'Scripting' started by HanbieRyu, Sep 8, 2018.

  1. HanbieRyu

    HanbieRyu

    Joined:
    Sep 2, 2018
    Posts:
    4
    (C#)Is there any way to get each gameObjects on contact with the collider inside OnCollisionStay? I saw that you can get the first one on contact or how many it is on contact with, but I have no idea how to get multiple gameObjects that it is on contact with individually. Anyone who knows how to do this, PLEASE HELP.
    [Sorry for bad English]
     
  2. wtrebella

    wtrebella

    Joined:
    Mar 18, 2013
    Posts:
    35
    If I'm understanding what you're looking for, you could do something like:

    Code (CSharp):
    1. List<GameObject> curObjects = new List<GameObject>();
    2.  
    3. void OnCollisionEnter(Collision collision)
    4. {
    5.     if (!curObjects.Contains(collision.gameObject))
    6.     {
    7.         curObjects.Add(collision.gameObject);
    8.     }
    9. }
    10.  
    11. void OnCollisionExit(Collision collision)
    12. {
    13.     if (curObjects.Contains(collision.gameObject))
    14.     {
    15.         curObjects.Remove(collision.gameObject);
    16.     }
    17. }
    This will make it so your curObjects list will contain all the currently colliding objects.
     
    crumby_shirt likes this.