- Home /
ScriptableObject asset loses reference after restarting Unity
I'm trying to serialize Class1. When I enter and exit Playmode, class1 is serialized properly. When I switch scenes, the data in class1 is still there. However, when I restart (close/open) Unity the reference to class1 is missing. Below is my code, can anyone pinpoint what I'm doing wrong here? Maybe, teach me also how to correctly save Class1 into an asset file? TIA!
SerializeMe.cs
using UnityEngine;
using UnityEditor;
using System.Collections;
[System.Serializable]
public class Class1 : ScriptableObject
{
public int num;
public void Init(int num)
{
this.num = num;
}
}
public class SerializeMe : MonoBehaviour
{
public Class1 class1;
public void Serialize1()
{
class1 = ScriptableObject.CreateInstance<Class1>();
class1.Init(1);
AssetDatabase.CreateAsset(class1, "Assets/Class1.asset");
AssetDatabase.SaveAssets();
}
public void Serialize2()
{
class1 = ScriptableObject.CreateInstance<Class1>();
class1.Init(2);
AssetDatabase.CreateAsset(class1, "Assets/Class1.asset");
AssetDatabase.SaveAssets();
}
void OnDrawGizmosSelected()
{
if (class1 == null)
{
Debug.Log("null");
return;
}
if (class1.num == 1)
{
Gizmos.color = Color.red;
}
if (class1.num == 2)
{
Gizmos.color = Color.green;
}
Gizmos.DrawSphere(Vector3.zero, 2f);
}
}
Editor Script:
using UnityEngine;
using UnityEditor;
using System.Collections;
[CustomEditor(typeof(SerializeMe))]
public class SerializeMeEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("Serialize1"))
{
((SerializeMe)target).Serialize1();
EditorUtility.SetDirty(target);
}
if (GUILayout.Button("Serialize2"))
{
((SerializeMe)target).Serialize2();
EditorUtility.SetDirty(target);
}
}
}
How my inspector looks like:
Answer by chrisjrock · Sep 04, 2014 at 01:52 PM
I have a very similar problem with a custom editor I'm working on. On Unity startup a ScriptableObject will be present, but after a few OnGUI calls, disappear. The reference is null.
Your answer
Follow this Question
Related Questions
Custom assets give Missing (Mono Script) 0 Answers
ScriptableObject stored in MonoBehaviour lost on quit 1 Answer
Difference between assigning a value in inspector and with a custom editor script 1 Answer
How to serialize a concrete derived class from generic ScriptableObject base 1 Answer
How to make a deep copy of a list of ScriptableObject derived types? 1 Answer