using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; using OctoCore.Navigation; [DisallowMultipleComponent] public sealed class PersistentWwiseFadeInPlayer : MonoBehaviour { private static PersistentWwiseFadeInPlayer _instance; [SerializeField] private AK.Wwise.Event _fadeInEvent; private const int BindRetryFrames = 120; private OctoSceneFade _boundFade; private Coroutine _bindRoutine; [RuntimeInitializeOnLoadMethod( RuntimeInitializeLoadType.SubsystemRegistration)] private static void ResetInstance() { _instance = null; } private void Awake() { if (_instance != null && _instance != this) { Destroy(gameObject); return; } _instance = this; // Required because DontDestroyOnLoad should preserve a root object. if (transform.parent != null) transform.SetParent(null, true); DontDestroyOnLoad(gameObject); } private void OnEnable() { SceneManager.sceneLoaded += OnSceneLoaded; } private void Start() { StartBinding(SceneManager.GetActiveScene()); } private void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoaded; if (_bindRoutine != null) { StopCoroutine(_bindRoutine); _bindRoutine = null; } Unbind(); } private void OnDestroy() { if (_instance == this) _instance = null; } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { StartBinding(scene); } private void StartBinding(Scene scene) { if (_bindRoutine != null) StopCoroutine(_bindRoutine); _bindRoutine = StartCoroutine(BindWhenAvailable(scene)); } private IEnumerator BindWhenAvailable(Scene scene) { for (int frame = 0; frame < BindRetryFrames; frame++) { OctoSceneFade fade = FindFade(scene); if (fade != null) { Bind(fade); _bindRoutine = null; yield break; } yield return null; } Debug.LogWarning( $"[{nameof(PersistentWwiseFadeInPlayer)}] " + $"Could not find OctoSceneFade for scene '{scene.name}'.", this ); _bindRoutine = null; } private static OctoSceneFade FindFade(Scene scene) { if (scene.IsValid() && scene.isLoaded) { foreach (GameObject root in scene.GetRootGameObjects()) { OctoSceneFade fade = root.GetComponentInChildren(true); if (fade != null) return fade; } } return OctoSceneFade.Instance; } private void Bind(OctoSceneFade fade) { if (_boundFade == fade) return; Unbind(); _boundFade = fade; _boundFade.OnFadeIn += OnFadeIn; } private void Unbind() { if (_boundFade != null) _boundFade.OnFadeIn -= OnFadeIn; _boundFade = null; } private void OnFadeIn() { if (_fadeInEvent == null) return; _fadeInEvent.Post(gameObject); } }