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

can i count how many objects a Cube is colliding with ?

Discussion in 'Scripting' started by sushanta1991, Sep 7, 2012.

  1. sushanta1991

    sushanta1991

    Joined:
    Apr 3, 2011
    Posts:
    305
    Hi Guys

    My Question is, can i count how many objects a Cube is colliding with ?
    Guys can you please suggest me if there is any way to do it?

    I was thinking to do it using tag, my idea was to add colliding object to an array than finding its length to know how many objects is colliding with my cube. But after some trial i can only add one Object that is colliding with my cube (but there is 3 objects that is colliding)

    Here is the code :
    Code (csharp):
    1.  
    2. #pragma strict
    3. var newA : Array;
    4. function Start () {
    5.  
    6. }
    7.  
    8. function Update () {
    9.  
    10. }
    11.  
    12. function OnCollisionEnter(hit : Collision)
    13. {
    14.     print(hit.collider.tag);
    15.     var x : GameObject = hit.collider.gameObject;  // This line only takes one colliding object, How can i take multiple objects.
    16.     newA = new Array(x);
    17.     print(newA.length);
    18. }
    19.  
     
    Last edited: Sep 7, 2012
  2. sushanta1991

    sushanta1991

    Joined:
    Apr 3, 2011
    Posts:
    305
    Here is the working code :
    Code (csharp):
    1.  
    2. var x : int;
    3. function Start () {
    4.  
    5. }
    6.  
    7. function Update () {
    8.  
    9. }
    10.  
    11. function OnCollisionEnter(hit : Collision)
    12. {
    13.     x++;
    14.     print("x" +x);
    15. }
    16.  
    Just need to put a int variable Inside OnCollisionEnter, and it will automatically increment the variable, the number of time it collide with other object :)
     
  3. RodrigoSeVeN

    RodrigoSeVeN

    Joined:
    Jul 10, 2010
    Posts:
    15
    I needed to check how many objects were colliding, but I had to check when all of them stopped colliding, so I did a "x--;" in the "Exit" version of the function. I was using triggers in my case. Thanks for the general idea!