Search Unity

Check if a GameObject collides with another GameObject

Discussion in 'Scripting' started by SwordSkill, Nov 28, 2013.

  1. SwordSkill

    SwordSkill

    Joined:
    Sep 30, 2013
    Posts:
    9
    Hello everyone, I just wanted to know if there is a way to check if a GameObject collides with another simply.
    In ActionScript for example, there is a Method that is called 'hitTest'. with that, you can determine easily if an Object is in collision with another object.

    for example in Flash:

    Code (csharp):
    1. if( firstObject.hitTest(secondObject) ){
    2.  print("Object A Collides with Object B");
    3. }

    In Unity you have to create a script that you will put in a GameObject that will be something like that:

    Code (csharp):
    1. #pragma strict
    2.  
    3. static public var collisionWithObjectB:boolean;
    4. public var ObjectB:GameObject;
    5.  
    6. function Start(){
    7.  collisionWithObject = false;
    8. }
    9.  
    10. function OnCollisionStay(collision:Collision){
    11.  if(collision == ObjectB){
    12.   collisionWithObjectB = true;
    13.  }
    14. }
    15.  
    16. function OnCollisionExit(collision:Collision){
    17.  if(collision == ObjectB){
    18.   collisionWithObjectB = false;
    19.  }
    20. }
    And after all of this we can check whether they collide or not, so I was looking for a way (if there is any.) to make this process faster. Thanks in advance.
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Maybe this :

    Code (csharp):
    1.  
    2. var IsColliding : boolean = false;
    3.  
    4. function OnCollisionEnter(other : Collision){
    5. if(other.gameObject.name == "ObjectB"){
    6. IsColliding = true;
    7. }
    8. }
    9.  
    10. function OnCollisionExit(other : Collision){
    11. if(other.gameObject.name == "ObjectB"){
    12. IsColliding = false;
    13. }
    14. }
    15.  
     
  3. SwordSkill

    SwordSkill

    Joined:
    Sep 30, 2013
    Posts:
    9
    What if I want to refer to two object from another script?
    For example, in Flash, you can check if two objects collide with one another by doing something like this:

    if(ObjectA.hitTest(ObjectB)){/*This will return true if those two object collide.*/}

    I simply don't want to be forced to create a script as a component in every GameObject that needs to be checked for collision purposes, but instead being able to refer to the collision between those two (or more.) from another script.
     
  4. nitrofurano

    nitrofurano

    Joined:
    Jun 7, 2019
    Posts:
    92
    this is exactly what i want to know as well - do anybody know how to do it?