Quick Tip for Constants

Here is a really quick and useful tip: use a static class for your constants! An Example:

namespace Constants
{
    public static class Paths
    {
        public static readonly string settings = Application.streamingAssetsPath + "/Settings.json";
        public static readonly string playerSettings = Application.streamingAssetsPath + "/Player.json";
    }

    public static class Tags
    {
        public const string board = "Board";
        public const string metal = "Metal";
        public const string net = "Net";
        public const string stick = "Stick";
    }
    public static class Layers
    {
        public static readonly int player = LayerMask.NameToLayer("Player");
        public static readonly int enemy = LayerMask.NameToLayer("Enemy");
    }
}

This is especially useful when dealing with strings. It will reduce memory allocations and typos. Also if any of these constants is changed, you won’t have to hunt for them in the whole project.

PS: Bonus points for using

gameObject.CompareTag(Constants.Tags.board);

instead of

gameObject.tag == Constants.Tags.board;

Leave a Reply

Your email address will not be published.