So, I have a custom object. Let’s call it Template. Within the Template, I have a list containing Actions. I have a few derived Action classes, let’s say they’re called Celebrate, Party, and Dance.
I’ve got my list of Actions set as a SerializedProperty, and I can select which derived class I want to use with a few buttons I’ve made. The problem is, I can’t figure out how to instantiate an Action object and add it to the list.
Anyone have any insight?
Also note, I do have to rely on inheritance for Actions, though I’m not picky about the root type that the Action class derives from.
Here’s one of a few things I’ve tried. Debugging shows that the array slot is being filled with something so it’s no longer null, but I can’t access any variables whatsoever, and using oAction.ToString () yields a blank string:
SerializedProperty oActionList = serializedObject.FindPropertyRelative ("actions");
Action oNewAction = Object.Instantiate (actions[(int)oAction]) as Action;
(oActionList.arraySize-1).objectReferenceValue = oNewAction;
It’s a little hard to tell with your snippet of code, but my first guess would be to look into having your Action class inherit from ScriptableObject and then you would use CreateInstance(). You can also you use the [System.Serializable] attribute on the Action class and just use the ‘new’ keyword (depending on what kind of data you’re trying to serialize). I won’t go into any more detail in case you’ve already checked out the avenues but please let me know if you need more information or I’m taking you down a path you’ve already been on.
Figured it out! Turns out to add the Action into the serialized array, it had to be in the form of a ScriptableObject or else it could not be of a derived class.
Then, because it was temporary data, it merely disappeared when the function ended and was cleaned up.
Instead, I had to add the Action to the Template’s asset file, then set the array slot’s reference ID to the new action’s ID, in that order.
AssetDatabase.AddObjectToAsset (oNewAction, Selection.activeObject);
(oActionList.arraySize-1).objectReferenceInstanceIDValue = oNewAction.GetInstanceID ();