- Home /
Serializing ScriptableObject into scene without writing to asset
Hey everyone,
I've been trying to get a ScriptableObject that's tied to a MonoBehaviour to serialize into the scene without writing it out as an asset. It seems like it's never serialized into the scene no matter what I do. I just wanted to see if it's just not how it's supposed to be used or if I'm missing something. Here's a basic rundown of how it's setup:
MonoBehaviour class that holds the ScriptableObject
public class TestObj : MonoBehaviour {
public TestSObj testSObj;
}
ScriptableObject class
[Serializable]
public class TestSObj : ScriptableObject {
public string name;
}
CustomEditor for Monobehaviour
[CustomEditor(typeof(TestObj))]
public class TestObjEditor : Editor {
TestObj testObj;
public override void OnInspectorGUI() {
testObj = (TestObj)target;
DrawDefaultInspector();
if (GUILayout.Button("Create")) { Create(); }
}
void Create() {
testObj.testSObj = ScriptableObject.CreateInstance<TestSObj>();
EditorUtility.SetDirty(testObj);
}
}
I apologize in advance for the terrible class names. Any insight into this issue would be greatly appreciated, thanks!
Answer by DiegoSLTS · Aug 12, 2016 at 03:24 AM
ScriptableObjects are assets, they're not serialized in the scene. It's like trying to serialize a texture's pixels in the scene instead of having an asset for that texture in the project.
You create a ScriptableObject asset of type TestObj, setup it's values in the asset, then add a reference to that asset in any script in your scene. What gets serialized is the reference, like any reference to other assets.
You can have different TestObj assets with different values.
EDIT: Also, I guess you found the tutorial that teaches how to create ScriptableObjects by writing a class that inherits from ScriptableObject an another class that creates the asset. There's an attribute that can be used when defining ScriptableObjects that handles all this for you: CreateAssetMenu
Check the official introduction: http://unity3d.com/es/learn/tutorials/modules/beginner/live-training-archive/scriptable-objects
It's long, but it explains everything you need to know and below it's the code that uses the attribute.