うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】GUILayoutOption のキャッシュクラス

GUILayoutOption は キャッシュして使うべきだが、毎度キャッシュ処理を書くのが面倒なので
キャッシュ用のクラスを作成、WidthとHeightしか対応していないため、その他の場合は別のキャッシュ機構が必要になる

internal static class CacheOption
{
    private static Dictionary<Vector2Int, GUILayoutOption> _dic = new Dictionary<Vector2Int, GUILayoutOption>();

    internal static GUILayoutOption Get(int width = 0, int height = 0)
    {
        var key = new Vector2Int(width, height);
        if (!_dic.ContainsKey(key))
        {
            if (width > 0)
                _dic.Add(key, GUILayout.Width(width));
            if (height > 0)
                _dic.Add(key, GUILayout.Height(width));
        }

        return _dic[key];
    }

    internal static GUILayoutOption Width(int width)
    {
        return Get(width, 0);
    }

    internal static GUILayoutOption Height(int height)
    {
        return Get(0, height);
    }
}

利用方法は今までとそこまで変わらない

if (GUILayout.Button("Button", CacheOption.Width(30)))
{
}