Last active
March 24, 2019 15:32
-
-
Save apkd/48a3121ffc4b2b31325ded86ce3b7ea4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
namespace Apkd | |
{ | |
namespace Internal | |
{ | |
sealed class MaterialPropertiesPreserver : MonoBehaviour | |
{ | |
#if UNITY_EDITOR | |
public static MaterialPropertiesPreserver Instance; | |
readonly Dictionary<Material, Material> originalMaterials = new Dictionary<Material, Material>(); | |
internal void Register(Material material) | |
{ | |
if (!originalMaterials.ContainsKey(material)) | |
originalMaterials[material] = Instantiate(material); | |
} | |
void OnDestroy() | |
{ | |
foreach (var kvp in originalMaterials) | |
kvp.Key.CopyPropertiesFromMaterial(kvp.Value); | |
} | |
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] | |
static void Initialize() | |
{ | |
Instance = new GameObject(nameof(MaterialPropertiesPreserver)).AddComponent<MaterialPropertiesPreserver>(); | |
Instance.gameObject.hideFlags = HideFlags.HideAndDontSave; | |
DontDestroyOnLoad(Instance.gameObject); | |
} | |
#else | |
internal void Register(Material material) { } | |
#endif | |
} | |
} | |
public static class ExtensionMethods | |
{ | |
public static void PreserveProperties(this Material material) | |
=> Internal.MaterialPropertiesPreserver.Instance.Register(material); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment