I’m building a custom editor to assemble a list of custom scripts and put them in a List<> on a script deriving from MonoBehaviour.
So far, my editor is working well. The point I’m stuck at is passing a variable from a list of types to ScriptableObject.CreateInstance<>
code snippets:
public class MyEditorClass: Editor
{
private List<Type> behaviorTypes = new List<Type>();
private int selectedType;
void OnEnable()
{
behaviorTypes = ReflectionVoodooThatGetsDesiredTypes(); // this works as expected
}
void OnInspectorGUI()
{
if (GUILayout.Button("Add", GUILayout.ExpandWidth(true)))
{
AddStuff();
}
}
void AddStuff()
{
Type childClass = behaviorTypes[selectedType];
AddBehavior(ScriptableObject.CreateInstance<childClass >()); // this doesn't work. what is the proper way to do what I'm conceptually trying to achieve here?
}
}
I have a base behavior class that inherits from ScritpableObject, and then several child classes that branch off of that to create a behavior tree. I have a List<> that stores all types that are derived from my base behavior class. I want to be able to select a type from that list and pass it to the ScriptableObject.CreateInstance() function.
I had this previously working using this line of code:
AddBehavior(behaviors[typeSelection].GetConstructors()[0].Invoke(new object[0]) as BaseBehavior);
this worked, but due to serialization child class types were being lost. So, now that I’ve switched over to ScriptableObject, my serialization problems are solved, but instantiation problems arise.
Thanks in advance
just to clarify, i do not know what type will be passed to ScriptableObject.CreateInstance, and I want that to remain flexible without having to build a large switch case, so that the behavior tree can be extended in the future with no updates to this chunk of code
– zombienceI don't think you can instantiate a scriptable object. Only Monobehaviors.
– jacobschellenbergScriptableObject.CreateInstance() is the preferred method for creating a ScriptableObject. if you try to create one via: new BehaviorObject(); // where BehaviorObject inherits from ScriptableObject you'll get a warning.
– zombiencebtw: [UnityEngine.Object.Instantiate][1] works for all objects derived from UnityEngine.Object (that includes even Mesh, Material, ... and should also work with ScriptableObject) :) [1]: http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html
– Bunny83Hmm, well, it is only a warning, but this warning pops up every time I try to use the class constructor via System.Reflection. I wanted to make sure that I do things properly to avoid any weird serialization problems later. The warning I'm seeing: AlternateExplode must be instantiated using the ScriptableObject.CreateInstance method instead of new AlternateExplode. UnityEngine.ScriptableObject:.ctor()
– zombience