Is it possible to prevent Unity from changing the playmode after the user has pressed the button?
Let's say I have a custom editor which may have a state which can't be properly serialized; if user changes Unity Editor mode at this moment, their changes will be lost.
It is an option to completely get rid of non-serializeable state, but this is the task of completely different complexity. Would like to avoid that.
UPD:
I've tested derHugo's answer with the following script:
using UnityEditor;
using UnityEngine;
namespace Innoactive.Hub.Training.Editors
{
[InitializeOnLoad]
public class ProveThatDudeWrongWindow : EditorWindow
{
private static ProveThatDudeWrongWindow windowInstance;
private string notSerializedString = "default";
static ProveThatDudeWrongWindow()
{
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
[MenuItem("Test/I'm damn sure he's wrong")]
private static void MenuItem()
{
if (windowInstance == null)
{
windowInstance = GetWindow<ProveThatDudeWrongWindow>();
}
windowInstance.notSerializedString = "some value";
}
[MenuItem("Test/Display current value")]
private static void DisplayCurrentNonSerializedValue()
{
windowInstance = GetWindow<ProveThatDudeWrongWindow>();
Debug.Log("string: " + windowInstance.notSerializedString);
}
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
{
EditorApplication.isPlaying = false;
}
Debug.Log("state: " + state);
}
}
}
Then I've done the following:
- Press
Test/I'm damn sure he's wrongoption to set non-serialized value fromdefaultvalue tosome value - Press
Test/Display current valueto make sure the value is changed - Press play button
- Press
Test/Display current valueto see current value. If it isdefault, derHugo's solution does not work, if it issome value, it works.
Result: derHugo is cool.