Skip to content

Instantly share code, notes, and snippets.

@brihernandez
Last active November 10, 2023 00:54
Show Gist options
  • Save brihernandez/8bef49567b1abd5b3f95fc6b35ab9916 to your computer and use it in GitHub Desktop.
Save brihernandez/8bef49567b1abd5b3f95fc6b35ab9916 to your computer and use it in GitHub Desktop.
Simple wrapper classes for handling layer related operations in Unity.
using UnityEngine;
/// <summary>
/// Convenience class for handling layer related operations and lookups in Unity.
/// </summary>
public readonly struct UnityLayer
{
/// <summary>
/// Name of the layer as defined in the Tags and Layers window in Unity.
/// </summary>
public readonly string Name;
/// <summary>
/// Bitmask value to be used when constructing a <see cref="LayerMask"/> for
/// operations such as raycasts.
/// </summary>
public readonly int Mask;
/// <summary>
/// ID for doing lookups and comparisons such as with <see cref="GameObject.layer"/>.
/// </summary>
public readonly int ID;
/// <param name="name">Name of the layer as it appears in the "Tags and Layers" window.</param>
public UnityLayer(string name)
{
Name = name;
Mask = LayerMask.GetMask(name);
ID = LayerMask.NameToLayer(name);
}
}
/// <summary>
/// Wrapper class for all the layers that the game uses. Can be accessed from anywhere.
/// </summary>
public static class LayerIDs
{
// These are some of the layers I use. Add/remove layers as needed for your game.
public static readonly UnityLayer Default = new UnityLayer("Default");
public static readonly UnityLayer Terrain = new UnityLayer("Terrain");
public static readonly UnityLayer Building = new UnityLayer("Building");
}
/* ==================================================
// Simple examples for using the LayerID class:
// Assign a layer to an object.
coolObject.layer = LayerIDs.Building.ID;
// Check if something is on a given layer.
var isHitbox = coolObject.layer == LayerIDs.Hitbox.ID;
// Construct a LayerMask for use in things like Raycasts.
var hitMask = LayerIDs.Terrain.Mask | LayerIDs.Hitbox.Mask;
// ================================================*/
@garettbass
Copy link

Suggestions:

  • public struct UnityLayer // no allocation
  • public readonly string Name; // constant
  • public static readonly UnityLayer Default = ...

@brihernandez
Copy link
Author

There's no reason these need to be mutable. Good catch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment