- Home /
Scriptable Object List values are always null
I need to save a list of base classes in a Scriptable Object, but currently all I'm seeing in the inspector is a list of null. That is the basic structure:
public class Node_Canvas_Object : ScriptableObject
{
public List<Node> nodes;
}
public abstract class Node : UnityEngine.Object
{}
[System.Serializable]
public class CalcNode : Node
{}
Node is an abstract class serving as a base for alot more like CalcNode, though when I save the ScriptableObject Node_Canvas_Object the List of Nodes (containg CalcNodes and others) just contains a lot of null's.
What do I need to take care of to make this work?
Answer by ThermalFusion · May 25, 2015 at 02:39 PM
Unity does not support serializing of inherited classes. You will need to use a class that unity serializes as a reference, like ScriptableObject. Take a look at this Answer for more information: http://answers.unity3d.com/questions/245604/does-unity-serialization-support-inheritence.html
Thanks for the answer and the link! I'm going to try out making the parent class also a Scriptable Object. Do I have to save it seperately, too? Without I'm getting Type $$anonymous$$ismatch ins$$anonymous$$d of null
I can save as an SubAsset now, but I'm having trouble identifying those when loading again. How would I go about that?
Got it so far, here's the way I took:
if (GUILayout.Button ("Load Canvas"))
{
Node_Canvas_Object OldNodeCanvas = Object.Instantiate<Node_Canvas_Object> (nodeCanvas); // Backup
nodeCanvas = null;
Object[] objects = AssetDatabase.LoadAllAssetsAtPath ("Assets/Node_Editor/Canvas.asset");
if (objects.Length == 0)
{ // Revert
Debug.Log ("No objects found in the save file!");
nodeCanvas = OldNodeCanvas;
return;
}
List<Node> nodes = new List<Node> ();
for (int cnt = 0; cnt < objects.Length; cnt++)
{ // Important Part
if (objects [cnt].GetType () == typeof(Node_Canvas_Object))
nodeCanvas = objects [cnt] as Node_Canvas_Object;
else if (objects [cnt].GetType ().IsSubclassOf (typeof (Node)))
nodes.Add (objects [cnt] as Node);
}
if (nodeCanvas == null)
{ // Revert
Debug.Log ("No NodeCanvas found in the save file!");
nodeCanvas = OldNodeCanvas;
return;
}
nodeCanvas.nodes = nodes;
Debug.Log ("Node Canvas Loaded!");
Repaint ();
}
With the code above this should make sense for everybody. Remember my base class, Node, now also inherits from ScriptableObject.
Just as an FYI, subclasses need to be in their own file or the serializer will have issues.
Your answer
Follow this Question
Related Questions
Wrong serialization when using ScriptableObject + [System.Serializable] + inheritance 2 Answers
Weird Custom Editor bug 1 Answer
SubClass Reference becomes BaseClass after Serialization 0 Answers
Calling a derived class (Serialized in a Scriptable Object) returns the super class. 1 Answer
ISerializationCallbackReceiver not working on ScriptableObject 2 Answers