Unity tips – avoiding collisions

Are you developing a Unity game and wondering how to make an object or group of objects NOT collide with certain other objects? Then read on…


The trick is to set the often ignored layer property for your objects and tweak the physics settings for your project


 

Adding a layer

While you can use one of the predefined layers, it could be could practice to use a custom layer for your custom collision behaviour. Go to Edit > Project Settings > Tags and Layers and just enter a name in the next available layer slot, like so:

Tags and layers


 

Here I’ve added 2 new layers: PlayerLayer and noPlayCollision, which have indecies of 9 and 10, respectively.

Setting a layer

I’m going to set my player object to the PlayerLayer and, for objects that I wish not to collide with the player, set their layer to noPlayerCollision. Select your game object or prefab and in the inspector panel, change the layer property from the drop-down (and ‘apply’ to the prefab, if necessary).

Object inspector

Editing physics settings

Global physics settings for your project (such as gravity and default collision behaviour) are controlled by the Physics Manager. To amend its settings, go to Edit > Project Settings > Physics.

Here, we untick the noPlayerCollision/PlayerLayer box in the Layer Collision Matrix, to tell the Physics Manager NOT to check for collisions between these layers.

Physics Manager

Something not mentioned much in forums and documentation is that a game object’s layer property can be changed at runtime to affect its behaviour dynamically – note that this property is actually an int (default: 0), see Unity’s documentation for more detail on this.

This trick could also be used to improve performance in a physics-heavy game or simulation, where collisions between certain types of objects are never going to happen. For example:collisions

InterServer Web Hosting and VPS
 

Leave a Reply