I don’t believe that Start() is ever executed in edit mode, even with the attribute. You may want to put it in a context menu-triggered function instead.
Start (and Awake) is executed in edit mode when you first place the component onto the object (or when you first load the scene)
AddListener adds a non-persistent listener to the UnityEvent, which do not show up in the editor and are not serialized. This only works at runtime.
The ones that show up in the editor are Persistent listeners. You can only add and remove them through the inspector, or using the UnityEditor namespace. Calling RemoveAllListeners at runtime only removes non-persistent listeners.
To add Persistent Listeners via scripting, use the UnityEventTools static class:
using UnityEngine;
using UnityEngine.Events;
using UnityEditor.Events;
[ExecuteInEditMode]
public class Foo : MonoBehaviour {
[SerializeField]
UnityEvent serializedEvent;
void Awake()
{
//So that it only creates the listener once, when the component is dragged on, not when the scene is loaded.
if (serializedEvent == null) {
serializedEvent = new UnityEvent ();
UnityEventTools.AddVoidPersistentListener (serializedEvent, Bar);
}
}
void Start()
{
serializedEvent.Invoke ();
}
public void Bar()
{
Debug.Log ("Bar Called.");
}
}
How would I be able to set the execution property of the registered Persistent Listener from the default “Runtime Only” to “Editor and Runtime” by script to actually be able to invoke the registered events also in editor mode?
public void RegisterEvents()
{
// registers persistent listener as "Runtime only"
UnityEventTools.AddVoidPersistentListener(modulesManager.OnModuleVariantsShowEvent, OnShowModuleVariants);
}
public void OnShowModuleVariants()
{
Debug.Log("OnShowModuleVariants");
// ...
}