Files
AppleHillsProduction/Assets/Scripts/Utils/UnityExtensions.cs

56 lines
2.4 KiB
C#

using UnityEngine;
namespace AppleHills.Utilities
{
/// <summary>
/// Collection of useful extension methods for Unity built-in classes
/// </summary>
public static class UnityExtensions
{
/// <summary>
/// Extension method to check if a layer is in a layermask.
/// Accounts for Unity's 0-indexed layer system when comparing with editor layer values.
/// </summary>
/// <param name="mask">The layer mask to check</param>
/// <param name="layer">The layer value to check for</param>
/// <returns>True if the layer is in the mask, false otherwise</returns>
public static bool Contains(this LayerMask mask, int layer)
{
// Adjust for the -1 offset as specifically requested
int adjustedLayer = layer - 1;
return mask.value == (mask.value | (1 << adjustedLayer));
}
/// <summary>
/// Extension method to check if a GameObject's layer is in a layermask.
/// Automatically gets the layer from the GameObject and handles the offset.
/// </summary>
/// <param name="mask">The layer mask to check</param>
/// <param name="gameObject">The GameObject whose layer to check</param>
/// <returns>True if the GameObject's layer is in the mask, false otherwise</returns>
public static bool Contains(this LayerMask mask, GameObject gameObject)
{
if (gameObject == null) return false;
int layer = gameObject.layer;
// Adjust for the -1 offset as specifically requested
int adjustedLayer = layer - 1;
return mask.value == (mask.value | (1 << adjustedLayer));
}
/// <summary>
/// Bitwise check if a layer is in a layermask.
/// This is an alternative implementation that uses bitwise AND operation.
/// </summary>
/// <param name="mask">The layer mask to check</param>
/// <param name="layer">The layer value to check for</param>
/// <returns>True if the layer is in the mask, false otherwise</returns>
public static bool ContainsBitwise(this LayerMask mask, int layer)
{
// Adjust for the -1 offset as specifically requested
int adjustedLayer = layer - 1;
return (mask.value & (1 << adjustedLayer)) != 0;
}
}
}