Skip to content

Instantly share code, notes, and snippets.

@apkd
Last active March 24, 2019 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apkd/48a3121ffc4b2b31325ded86ce3b7ea4 to your computer and use it in GitHub Desktop.
Save apkd/48a3121ffc4b2b31325ded86ce3b7ea4 to your computer and use it in GitHub Desktop.
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