Home > OS >  How to check Collision detection for GameObjects of same prefab (Unity)
How to check Collision detection for GameObjects of same prefab (Unity)

Time:08-10

(For 2D Project) I created a gameObject and made it a prefab. Now when the game starts, the prefab is used to instantiate gameObjects and they all should check if they collide with one another.

I tried other unity's collision methods but it didn't work. They either kept colliding with themselves (their own rigidbody) or it didn't work at all.

I'm new to unity and learning things. I searched every where but didn't get my question solved. I'll appreciate any help, Thank you!

Prefab is loaded and Instantiated as such..

GameObject tile = Instantiate(Resources.Load("Prefabs/Tile") as GameObject); 

Its a basic gameObject having SpriteRenderer 2D.

I used Box Collider 2D and Rigidbody 2D components on that prefab - enter image description here

Another issue is that you're bailing on the operation if the triggerBody is null. As I mentioned at the start, you're not explicitly setting the triggerBody in your code, so if it's also not set in the prefab then you'd abort here even if the collider options were set correctly.

Finally, and probably most importantly, is this snippet doesn't make sense:

if (other.attachedRigidbody == triggerBody) {  
    Debug.Log("Collision!");  
}

What you're saying here is that you want there to be a collision if the other rigidbody is the same as the local rigidbody. This would ensure the behavior you described in your post,

They either kept colliding with themselves (their own rigidbody) or it didn't work at all.

You're only calling it a collision if they're colliding with themselves! The way to check if it's NOT self-colliding is to make sure the other.attachedRigidbody is NOT equal to the local triggerBody!

What you would want instead would be:

if (other.attachedRigidbody != triggerBody) {  
    Debug.Log("Collision!");  
}
  • Related