This script is attached to an object in a scene, and all I want is for the OnSceneClosingEvent
event to fire when I’m closing the scene in the editor (like for example I open a new scene or reload the same scene).
But the event never fires. It doesn’t throw an error but the things I’ve assigned to it in the inspector don’t trigger (which are just simply SetActive()
calls).
Otherwise the EditorSceneManager.sceneClosing
works. It prints to the log, I can do stuff inside, but the UnityEvent
won’t fire for some reason.
using System;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
[InitializeOnLoad]
public class EditorSceneEvents : MonoBehaviour
{
public UnityEvent OnSceneClosingEvent;
private EditorSceneEvents()
{
Debug.Log("EditorSceneEvents constructor");
EditorSceneManager.sceneClosing -= OnSceneClosing;
EditorSceneManager.sceneClosing += OnSceneClosing;
}
private void Reset() {
Debug.Log("EditorSceneEvents Reset");
}
private void OnDestroy()
{
EditorSceneManager.sceneClosing -= OnSceneClosing;
}
private void OnSceneClosing(Scene scene, bool removingScene)
{
Debug.Log("OnSceneClosing", scene.name);
OnSceneClosingEvent?.Invoke();
}
}