Search Unity

Can sceneLoaded arrive after OnEnable?

Discussion in 'Scripting' started by Braza, Aug 29, 2022.

  1. Braza

    Braza

    Joined:
    Oct 11, 2013
    Posts:
    136
    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?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class DoNotDestroyOnLoad : MonoBehaviour
    7. {
    8.     [SerializeField]
    9.     bool keepForCombatScene;
    10.     [SerializeField]
    11.     bool keepForMenuScene;
    12.  
    13.     public bool KeepForCombatScene { get => keepForCombatScene; set => keepForCombatScene = value; }
    14.     public bool KeepForMenuScene { get => keepForMenuScene; set => keepForMenuScene = value; }
    15.  
    16.     private void Awake()
    17.     {
    18.         DontDestroyOnLoad(gameObject);
    19.     }
    20.  
    21.     public void DestroySelf()
    22.     {
    23.         Destroy(gameObject);
    24.     }
    25.  
    26.     void OnEnable()
    27.     {
    28.         SceneManager.sceneLoaded += OnSceneLoaded;
    29.     }
    30.  
    31.     void OnDisable()
    32.     {
    33.         SceneManager.sceneLoaded -= OnSceneLoaded;
    34.     }
    35.  
    36.     private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    37.     {
    38.         if (!keepForMenuScene && scene.name == "MainMenu")
    39.         {
    40.             DestroySelf();
    41.         }
    42.         if (!keepForCombatScene && scene.name.Contains("Combat"))
    43.         {
    44.             DestroySelf();
    45.         }
    46.     }
    47. }
    48.  
     
  2. Braza

    Braza

    Joined:
    Oct 11, 2013
    Posts:
    136
    Yoreki likes this.