Using Layers to Avoid Unwanted Collisions in Unity

Behold our Skeleton, he has two box colliders on him as you can see. One is for his body and the other is for his weapon.

I want to be able to constantly check if the weapon collider hits the player, in an On Trigger Enter Method. The problem is the weapon collider will collide with the other collider on the skeleton and register false hits.

One way to solve this problem is to put the colliders on separate layers. Then adjust the project settings so that the two layers ignore each other. This is done in a couple of quick steps.

First let’s add a layer for both enemy and enemy weapon.

Next we set the layer of the skeleton sprite to be on the enemy layer. We then set the layer of the skeleton’s weapon to be on the enemy attack layer:

Now that they are on different layers, all we need to do is set Unity so that the layers ignore each other. This is done by accessing Edit → Project Settings. When the menu pops up choose Physics 2d on the left side. Scroll down to the bottom to see the following grid:

Uncheck the box corresponding to where enemy and enemy attack cross. Now the layers will ignore each other. Of course, make sure the weapon attack and player layer (or whatever layer the player is on) are checked for each other.

That’s all there is to it.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jon Jenkins

Jon Jenkins

A Unity Developer, interested in all things Unity.