I’m trying to save a MethodInfo to a script through an editor window. When I create the script that should remember the method info it works well but whenever unity recompiles, (Run-Time, script has changed or unity restarts) the MethodInfo variable has been reset to null. I’ve tried serializing the class that saves it and making the MethodInfo a SerializedField,
What happens precisely:
I select a Component belonging to a GameObject and a MethodInfo belonging to that component. Then create a new GameObject containing a script that has variables for GameObject, Component & MethodInfo. I then set those variables to the selected vars. Untill now it works.
When unity compiles again the GameObject and Component are still saved but the MethodInfo has turned to null.
Any help would be greatly appreciated.
MethodInfo is not serializable by Unity. You would have to serialize it yourself. I recently created two helper classes to tackle this in Unity:
SerializableMethodInfo depends on SerializableType so you would need both.
You can simply define a variable in a MonoBehaviour or ScriptableObject (which includes the Editor and EditorWindow class) like this:
public SerializableMethodInfo method;
In MonoBehaviour derived classes the inspector will already create an instance for you. So you can simply assign a MethodInfo to the public “methodInfo” variable:
MethodInfo info;
method.methodInfo = info;
At other places like inside an editor / editorwindow you might want to simply create a new instance like that:
MethodInfo info;
method = new SerializableMethodInfo(info);
This should serialize it automatically into primitive types that Unity can serialize and also deserialize it automatically whenever Unity deserializes that field.
The class serializes the containing class type as “SerializableType” and the method name as string. In addition it also serializes the parameter types as a List of SerializableTypes. That way it should be possible to serialize most kinds of MethodInfos. At the moment i think it doesn’t support generic parameters on the method itself (like GetComponent<T>()
). For that we would probably need to include the generic type parameter definition and reconstruct the MethodInfo from the generic MethodInfo using the MakeGenericMethod method.
edit
Of course Editor and EditorWindow instances only hold information for the current session / viewed object. If you want information to persist you would have to create a ScriptableObject which you store as asset in your project which you can reload next time.
I’m not 100% certain, but I think in order for variables to be saved between sessions and compilation, they have to be written to a file and then read from later.