Ignoring collisions with layers

In addition to the IgnoreCollision() command of the Physics class, we can use the Layers built into Unity in order to tell the physics engine which objects should not collide with one another. By placing objects onto opposing layers and deselecting them within the Physics settings Layer Collision Matrix, we are telling Unity not to register collisions with objects added to those layers.

Let's begin by creating two new layers. Open the Tag & Layers settings by navigating to Edit | Project Settings | Tags & Layers. Beneath the existing Tags in your project, you will see a list of built-in layers and, beneath that, starting from User Layer 8:

Add a new user layer for Weapon as shown in the screenshot. Simply press return to confirm. We chose Weapon instead of Bullet or Projectile, because we will be using it also for the hand collider punch later in Chapter 13, Optimization and Final Touches. Next, to adjust the configuration of how these layers interact, go to Edit | Project Settings | Physics.

Expand the settings for Layer Collision Matrix at the bottom, and deselect where these two layers intersect:

This sets up the layers to ignore collisions with one another; now we can simply assign our objects to these layers. Select the Warrior_RM player hero in the Hierarchy and, at the top of the Inspector, select Player from the Layers drop-down menu. You will be prompted to assign the layer Player to children GameObjects, choose to do so. Now, select the stone prefab in the Prefabs folder of the Project panel, and use the same approach to set this prefab's layer to Weapon.

We now have two safeguards in place to stop our stone projectile from interacting with the player itself, finding solutions such as this is an important part of minimizing bugs toward the end of your game's development.