Can sceneLoaded arrive after OnEnable?

I’m trying to make a component that allows objects to travel from Menu scene to Combat scene or otherwise, but not Menu-Combat-Menu to avoid duplication and other side effects.

I have the following component. It’s problem is that if I have an object on the Menu scene with keepForMenuScene = false it gets destroyed on creation, while my expectation was that OnEnable is executed after scene is loaded and sceneLoaded is fired. How is that?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class DoNotDestroyOnLoad : MonoBehaviour
{
    [SerializeField]
    bool keepForCombatScene;
    [SerializeField]
    bool keepForMenuScene;

    public bool KeepForCombatScene { get => keepForCombatScene; set => keepForCombatScene = value; }
    public bool KeepForMenuScene { get => keepForMenuScene; set => keepForMenuScene = value; }

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }

    public void DestroySelf()
    {
        Destroy(gameObject);
    }

    void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnDisable()
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (!keepForMenuScene && scene.name == "MainMenu")
        {
            DestroySelf();
        }
        if (!keepForCombatScene && scene.name.Contains("Combat"))
        {
            DestroySelf();
        }
    }
}

Unity - Manual: Execution Order of Event Functions answer the question. Sorry for impatience.

1 Like