Unity 2D Mobile Adventure: Appointing Collision Layers

Objective: Create new layers assigned to the player and enemies to prevent unwanted collision events

Josh P (Pixel Grim)
Unity Coder Corner
3 min readSep 26, 2023

--

Today, I will be experimenting with layers in Unity to prevent my enemies from accidentally attacking other enemies and the players from damaging themselves. Currently, in my game for both my Skeleton and Player, I have a child object labeled HitBox. This Hitbox object is only enabled when the sprite attacks and detects when an attack has successfully collided with another thing.

Attack Method

The issue is the collider for the attack hitbox on the player, and the skeleton overlaps with its sprite’s collider. This means that when the player swings its sword, it would try to pull it’s IDamage Interface component and then deal damage to itself.

    private void OnTriggerEnter2D(Collider2D collision) {
if (collision.TryGetComponent<IDamage>(out IDamage mon)) {
if(!targetHit) {
mon.Damage(1);
targetHit = true;
StartCoroutine(ResetDamageRoutine());
}
}

}

Solution Collision Layers

The solution was to create “two” layers, one assigned to the sprites and another linked to the weapon.

For the player, I created a player layer and a sword layer.

On the player’s parent object, I assigned the layer to the ‘player.’ Then, for the hitbox, I set the layer to sword. Doing this allows me to control what layer the sword can interact with using the project's settings.

Next, I went to the top and select EDIT -> PROJECT SETTINGS -> PHYSICS 2D. Here I am able to select the layers I want the player’s sword to interact with and not interact with.

Down below, I uncheck the box where the player and sword cross paths. This will notify Unity to make sure that layers will ignore each other. Therefore preventing my player from damaging itself! Easy stuff :).

--

--