Created
June 4, 2018 14:52
-
-
Save foxor/80c7260cf1b4b899f9816c34a1d48b29 to your computer and use it in GitHub Desktop.
Unity will serialize changes to scriptable objects to disk in edit mode. To avoid this, you need to instantiate objects, but only in edit mode. This script automates this process efficiently, and with minimal API overhead.
This file contains hidden or 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; | |
[System.Serializable] | |
public abstract class AutoInstantiate<T> where T : Object | |
{ | |
[SerializeField] | |
private T data; | |
#if UNITY_EDITOR | |
private static Dictionary<T, T> instantiatedVersions = new Dictionary<T, T>(); | |
private T instantiated; | |
#endif | |
public T value | |
{ | |
get | |
{ | |
return this; | |
} | |
} | |
public static implicit operator T(AutoInstantiate<T> source) | |
{ | |
#if UNITY_EDITOR | |
if (source.instantiated) | |
{ | |
return source.instantiated; | |
} | |
T cached; | |
if (!instantiatedVersions.TryGetValue(source.data, out cached)) | |
{ | |
cached = instantiatedVersions[source.data] = Object.Instantiate<T>(source.data); | |
} | |
return source.instantiated = cached; | |
#else | |
return source.data; | |
#endif | |
} | |
} |
This file contains hidden or 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 UnityEngine; | |
public class AutoInstantiateTest : MonoBehaviour { | |
public AutoSharedFloat autoVersion; | |
void Start () | |
{ | |
DoSomething(autoVersion); | |
} | |
private void DoSomething(SharedFloat sharedVersion) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment