forked from mob-sakai/SoftMaskForUGUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaterialCache.cs
More file actions
82 lines (69 loc) · 2.31 KB
/
Copy pathMaterialCache.cs
File metadata and controls
82 lines (69 loc) · 2.31 KB
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
78
79
80
81
82
using System.Collections.Generic;
using System;
using UnityEngine;
namespace Coffee.UISoftMask
{
internal class MaterialEntry
{
public Material material;
public int referenceCount;
public void Release()
{
if (material)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
UnityEngine.Object.DestroyImmediate(material, false);
else
#endif
UnityEngine.Object.Destroy(material);
}
material = null;
}
}
internal static class MaterialCache
{
static readonly Dictionary<Hash128, MaterialEntry> s_MaterialMap = new Dictionary<Hash128, MaterialEntry>();
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
private static void ClearCache()
{
foreach (var entry in s_MaterialMap.Values)
{
entry.Release();
}
s_MaterialMap.Clear();
}
#endif
public static Material Register(Material material, Hash128 hash, Action<Material> onModify)
{
if (!hash.isValid) return null;
MaterialEntry entry;
if (!s_MaterialMap.TryGetValue(hash, out entry))
{
entry = new MaterialEntry()
{
material = new Material(material)
{
hideFlags = HideFlags.HideAndDontSave,
},
};
onModify(entry.material);
s_MaterialMap.Add(hash, entry);
}
entry.referenceCount++;
//Debug.LogFormat("Register: {0}, {1} (Total: {2})", hash, entry.referenceCount, materialMap.Count);
return entry.material;
}
public static void Unregister(Hash128 hash)
{
MaterialEntry entry;
if (!hash.isValid || !s_MaterialMap.TryGetValue(hash, out entry)) return;
//Debug.LogFormat("Unregister: {0}, {1}", hash, entry.referenceCount -1);
if (--entry.referenceCount > 0) return;
entry.Release();
s_MaterialMap.Remove(hash);
//Debug.LogFormat("Unregister: Release Emtry: {0}, {1} (Total: {2})", hash, entry.referenceCount, materialMap.Count);
}
}
}