Unity: Using Layers instead of Tags

One of the first mechanics I came across when learning simple game programming in Unity was objects identifying other objects. Whether it be a collider collision, raycast or other function you require a way to identify the object and decide what to do about the object you have found.

Basic tutorials cover using tags and layers to identify objects and their purpose, but almost all of these tutorials use string comparisons. String comparisons are a very inefficient way to implement logic. Don’t get me wrong; they are a very simple and easy way to learn basic Unity approaches, but they aren’t the most scalable.

Unity Collision Documentation - Tags
Example from the Unity documentation on using tags

Its often a good idea to get in the habit of writing efficient code early on to prevent having to refactor an entire project 6 months later.

With this in mind I investigated deeper. Tags can only be compared by string comparisons, but Layers have an integer value in addition to their string “name” component. With this connection we can easily use an integer LayerMask to perform actions such as (but not limited to);

  • limit a RayCast to register hits only against a specific Layer (or Layers)
  • check a GameObjects layer value in a collision or trigger
Unity LayerMask Documentation - string to int
Example from the Unity documentation on using LayerMasks

This works great, and we can make the “Wall” input into a property on our script so the implementation is more flexible.

Next Up: Checking a GameObjects layer against multiple LayerMasks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: