Skip to content

Instantly share code, notes, and snippets.

@foxor
Created June 4, 2018 14:52
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 foxor/80c7260cf1b4b899f9816c34a1d48b29 to your computer and use it in GitHub Desktop.
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.
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
}
}
using UnityEngine;
public class AutoInstantiateTest : MonoBehaviour {
public AutoSharedFloat autoVersion;
void Start ()
{
DoSomething(autoVersion);
}
private void DoSomething(SharedFloat sharedVersion) {}
}
using UnityEngine;
// Example usage:
[CreateAssetMenu]
public class SharedFloat : ScriptableObject
{
public float data;
}
// This class is required to get the inspector to draw
[System.Serializable]
public class AutoSharedFloat : AutoInstantiate<SharedFloat>{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment