Working with Collision Layers in Unity

Esteban Ibarra
3 min readAug 15, 2021

Now that our Hitboxes are set up, let’s create an Attack script. Place it in the Player directory and attach it to the Hit_Box.

We’ll be using the OnTriggerEnter2D method to detect hits, let’s set it up:

and trying it out, we run into our first challenge. Our hit collider is actually hitting our own players collider!

One solution to this is to check the name of what’s being hit, and if the player is, ignore it by writing a return. There is also Unitys layer system that can resolve the issue a little more elegantly. We can create a sword layer, and once the player is on their own layer, we can make it so the sword layer can ignore the player layer but still affect others.

Select the hitbox, and we’ll see it’s on a default layer, let’s create a Sword layer, select hitbox again, and assign it to the newly created Sword layer.

Now we need to go into the physics options and turn off interaction between sword and player but the player doesn’t have its own layer right now so let’s create one. Go ahead and say yes when it asks if you want to assign the children as well.

Because the Hitbox was reassigned to the player layer, go back and reassign it to the Sword layer.

Next, go into preferences and in physics settings, we can go to the player and uncheck interaction with sword.

Now if we swing our sword, there will be no interaction with the player!

Now let’s see if we recognize the enemy…

We’re all set! Tomorrow we’ll continue programming the attack.

--

--