summaryrefslogtreecommitdiff
path: root/Assets/Scripts/Common/MaterialCache.cs
blob: 8d8ed9398e3dbb2db1db465ffa8eee32dc0329c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEngine;
using System.Text;
using UnityEngine.UI;

namespace Coffee.UIEffects
{
    public class MaterialCache
    {
        static Dictionary<Hash128, MaterialEntry> materialMap = new Dictionary<Hash128, MaterialEntry>();

        private class MaterialEntry
        {
            public Material material;
            public int referenceCount;

            public void Release()
            {
                if (material)
                {
                    UnityEngine.Object.DestroyImmediate(material, false);
                }

                material = null;
            }
        }

#if UNITY_EDITOR
        [UnityEditor.InitializeOnLoadMethod]
        private static void ClearCache()
        {
            foreach (var entry in materialMap.Values)
            {
                entry.Release();
            }

            materialMap.Clear();
        }
#endif

        public static Material Register(Material baseMaterial, Hash128 hash,
            System.Action<Material, Graphic> onModifyMaterial, Graphic graphic)
        {
            if (!hash.isValid) return null;

            MaterialEntry entry;
            if (!materialMap.TryGetValue(hash, out entry))
            {
                entry = new MaterialEntry()
                {
                    material = new Material(baseMaterial)
                    {
                        hideFlags = HideFlags.HideAndDontSave,
                    },
                };

                onModifyMaterial(entry.material, graphic);
                materialMap.Add(hash, entry);
            }

            entry.referenceCount++;
            return entry.material;
        }

        public static void Unregister(Hash128 hash)
        {
            MaterialEntry entry;
            if (!hash.isValid || !materialMap.TryGetValue(hash, out entry)) return;
            if (--entry.referenceCount > 0) return;

            entry.Release();
            materialMap.Remove(hash);
        }
    }
}