Creating Attack Script and Collision Layers!

addam davis
4 min readDec 3, 2021

--

Objective: Create a script to handle the player’s attacks.

In the last tutorial we created a hitbox for our players weapon. In this tutorial we are going to work out a script to handle the player’s attacks. If you followed along with the previous tutorial than you should have a hitbox, with a collider and a rigidbody.

Let’s begin by creating a new script named “Attack”

Attach this new script to the hitbox.

Open the script and remove the default methods.

We are going to use On Trigger Enter D to determine if we have hit something.

For testing purposes we want to print out the name of what our hitbox colliders hits.

Now play the game and let’s see what the console prints out when we attack.

As you can see, our sword collided with our player. We need to create a physics layer for our hitbox, which is essentially our sword. Select the hitbox, at the top of the inspector we have a drop down option for layer. Select Add Layer.

This will open a window and we want to create a new layer in the first layer available, for me, that is layer 9.

Select hitbox again and now when you select the drop box for layer set the layer to the Sword layer.

We also want to make our player to be on a “Player” layer so make a layer for the player and set it as well.

When you change the player layer it will ask you if you want to change the layer for all the child objects as well. Select yes, then go back to the hitbox and change it back to the sword layer.

Now we need to tell Unity to ignore the sword layer on our Player. To do this we need to navigate to Edit > Project Settings

This open the project setting window. Select physics 2D.

Scroll down and you will see the layer collision matrix.

We want the sword to ignore the player so unselect where the two cross.

Now when we test our game we will no longer detect the player when we attack. Now you know the basics of working with collision layers. Don’t be afraid to experiment with your Layer Collision Matrix, and I’ll see you in the next tutorial!

--

--