Here is my situation: I have an editor script which can perform a bunch of tasks. Whether or not it executes a function is based on some simple bools which by default are set to false. It’s up to the user to set them to true. It looks something like this:
[ExecuteInEditMode]
class MyScript : MonoBehaviour
{
// user can change these from the inspector
public static bool performTaskA = false;
public static bool performTaskB = false;
// update function is added to EditorApplication.update
void static Update()
{
if (performTaskA)
taskA();
if (performTaskB)
taskB();
}
}
My problem is whenever a script (any script) is compiled, the bools get reset to their default value of false. How can I get around this?
The editor will unload (and then reload) all assemblies when compiling; any transient data in memory will be lost during that process. That’s by design, but it can bite you if you’re not expecting it.
Editor scripts need to be aware of this, so they can compensate for it.
If you have a lot of data you need to serialize, you might do it using components in a scene, prefab, or ScriptableObject. I’ve also seen plugins that use JSON files and the like.
In your case, it looks like you have only a few simple fields, so you can probably use something lightweight like EditorPrefs?
EditorPrefs.SetBool("performTaskA", true);
...
if (EditorPrefs.GetBool("performTaskA")) {
taskA();
}
First of all that’s not an editor script. It’s a normal runtime script which just also runs at edit time (due to ExecuteInEditMode). MonoBehaviour scripts are always runtime scripts and will be part of your build game.
Besides that, when Unity recompiles a script, the whole scriptine environment is reloaded. So basically everything is lost. However Unity does serialize everything before the reload and recreates and deserializes everything afterwards, but the usual serialization rules apply. So static variables aren’t serialized since they don’t belong to an instance.
Using static variables can cause a lot of problems so it’s generally better to use instance variables. Since you didn’t showed the code which actually sets those booleans nor did you explain how those are actually set, i can’t offer you a solution since there are many ways to do this. Give us some more information.