- Home /
Persistently changing variables from custom editor
Hi everyone,
I have a script that has a custom class as a field, such as this:
public class MyClass : Monobehaviour{
public GameObject prefab; // a prefab that has a MyClass component
public SomeClass someClass;
}
public class SomeClass{
public int x;
public SomeClass(int _x){
x = _x;
}
}
What I'm trying to do is instantiate gameobjects with a MyClass component attached to them via a custom inspector for MyClass. Specifically, I want to set the someClass field to a specific value. Im currently trying it as follows:
[CustomEditor (typeof(MyClass))]
public class MyClassEditor : Editor{
public override void OnInspectorGUI() {
DrawDefaultInspector();
MyClass mc = (MyClass) target;
if(GUILayout.Button("button")) {
GameObject go = (GameObject) Instantiate(mc.prefabToInstantiate);
go.GetComponent<MyClass>().someClass.x = 1;
}
}
}
This does indeed instantiate the desired object and sets x to 1. However, as soon as I start the game, the field x is not set to 1 anymore. Is there any way to make this value persistent, even when entering play mode?
Cheers.
Answer by anilhdas · Oct 10, 2017 at 03:30 PM
You will need to make the SomeClass
serializable for it to retain the data.
So what happens here is, when unity enters playmode, all the data that is stored in C# side (like the values in the inspector) is serialized and restored back after the assemblies are reloaded.
UPDATE: In case if you're wondering why did I specify "C# side", Unity's core engine code is split into 2 parts, managed (C#) and native (C++). In order to change the state of the editor (like Enter / Exit playmode for example), Unity undergoes an internal assembly reload.
So any data that needs to survive this assembly reload should be serializable by the editor.
Answer by WickedSicked · Oct 10, 2017 at 11:39 AM
I got it to work by making SomeClass inherit from ScriptableObject. I'm not sure exactly why this solves the problem, but it does. Maybe this will help someone in the future.
Your answer
Follow this Question
Related Questions
Custom editor, serialize and prefab issue 0 Answers
Custom Editor for Monobehavior with custom property not retaining Gameobject references 0 Answers
Custom inspector variable resets automatically 1 Answer
Custom Inspector - Method Selector just like Button OnClick()? 1 Answer
Is it possible to create a custom gettter/setter on SerializedProperty ? 0 Answers