Is there a way to get maximum number of Layers Unity allows?

I know that Unity allows a maximum of 31 layers, but I was hoping there was either a way to dynamically grab the max number of layers (31) or possibly a const value somewhere in the Unity API.

Simply trying to avoid hard coding 31.

Thanks!

First, Unity allows a maximum of 32 layers, 0-31, not 31. The reason for this is because Unity uses ints for layermask which has a size of 32 bits. If the nth layer is in a layermask then the nth bit is 1 otherwise the nth bit is 0.

I would be surprised if there was a way to grab the max number of layers using the Unity API. However you can define it yourself. i.e.

public class Layer {
    public const int max=32;
}

or if you want to use the size of int (4 bytes=32 bits)

public class Layer {
    public const int max=sizeof(int)*8;
}

Then you can call the max value of layer using Layer.max from whatever script you want, i.e.

using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
    void Start() {
        Debug.Log(Layer.max);
        Debug.Log(33<Layer.max);
    }
}

UnityEngine.SortingLayer.layers.Length;