We don’t want the player chopping off their leg when they attack, do we?
Objective: Working with collision layers in Unity
After getting the hitbox working for the character, we can now look at being able to attack with that hitbox.

Later we will be adding in an interface to be able to look for instead of going through and looking to see if we hit a skeleton, moss giant, spider, chest, etc.
So for now we can add in an attack script and attach it to the sword. Inside the script, we can just do an on trigger enter to check if we hit something.

And some code to check for that interface that we will be looking into in the next article, so for now, don’t worry about it too much.

All it’s doing is checking if what we hit has a damage interface and calling the damage method if it does.
At the moment though, if we leave this as is we will run into the problem of the player dying every time we swing our sword.

This is because the player is using the same layer as the sword and is using the same interface it’s looking for. We can fix this by using the layers in unity.
First, make a new layer for the sword.


Next, we can set the sword to the new layer. Since the sword is the hitbox, we can change that layer.

Although we will need to separate the player out as well. if we remove the collision of the sword with the layer the player is on, this will end up with the sword not being able to hit anything.
Make another layer and name it player.


And change the player to that layer, when it asks if you want to change all the children to that layer too, click yes.

Now we can change back to the hitbox/sword and change its layer back to the sword layer.

Even with all that the player will still end up killing themself when they attack, I mean what goes? this was meant to fix it… well there is another setting we have to change so the layers don’t do anything physics between the layers which just means they won’t collide.
Go to the project settings Edit>Project Settings…

Change to the Physics 2D tab.

Down the bottom, there is the triangle with what layer can interact with what layers, we want to go to the players and disable the swords/swords and disable the players.

Now with that turned off, we can now attack without the player dying as well.

With that, we have fixed a bug and learnt about something new. Next, we will take a look at that interface I was talking about at the start. See you there!