Search Unity

Question Unity reports error saying the script (observer) was destroyed after chaging scenes, but i wasnt

Discussion in 'C# Job System' started by Crydson, Apr 16, 2023.

  1. Crydson

    Crydson

    Joined:
    Nov 17, 2020
    Posts:
    3
    i dont know how things works on this forum but i will try to be clear as possible

    For the context i have two scenes, Menu and SampleScene (where the game happens),

    upload_2023-4-16_19-9-18.png

    After loading from the Menu to SampleScene i get the error MissingReferenceException: The object of type 'cs_UI_MenuPause' has been destroyed but you are still trying to access, it only occurs when loading to its scene, when starting from there it works normal.

    So what im doing is have an Observer subscribed to an Event that says when the game is paused and not, i have the cs_UI_MouseEvents where i basically put all of my UI events. and the location of the trigger.

    Code (CSharp):
    1.  public class cs_UI_MouseEvents : MonoBehaviour
    2. {
    3.  
    4.     public delegate void pauseAction();
    5.     public static event pauseAction OnPause;
    6.  
    7.     public delegate void pauseActionOff();
    8.     public static event pauseActionOff OffPause;
    9.  
    10.    
    11.     private void Update()
    12.     {
    13.         PausePressVoid();
    14.     }
    15.  
    16.  
    17.     void PausePressVoid()
    18.     {
    19.         if (Input.GetKeyDown(KeyCode.Tab))
    20.         {
    21.             paused = !paused;
    22.  
    23.             if (paused == true)
    24.             {
    25.                 if (OnPause != null) OnPause();
    26.             }
    27.             else
    28.             {
    29.                 if (OffPause != null) OffPause();
    30.             }
    31.         }
    32.     }
    33. }
    And the cs_UI_MenuPause wich is the observer


    Code (CSharp):
    1. public class cs_UI_MenuPause : MonoBehaviour
    2. {
    3.    
    4.     private void OnEnable()
    5.     {
    6.         cs_UI_MouseEvents.OnPause += ActivePause;
    7.         cs_UI_MouseEvents.OffPause += DesactivePause;
    8.     }
    9.  
    10.     private void OnDisable()
    11.     {
    12.         cs_UI_MouseEvents.OffPause -= ActivePause;
    13.         cs_UI_MouseEvents.OffPause -= DesactivePause;
    14.     }
    15.  
    16.    
    17.     void ActivePause()
    18.     {
    19.         gameObject.transform.GetChild(0).gameObject.SetActive(true);
    20.        
    21.     }
    22.  
    23.     void DesactivePause()
    24.     {
    25.         gameObject.transform.GetChild(0).gameObject.SetActive(false);
    26.     }
    27. }
    The problem i get is, after loading to the SampleScene it says the Observer script (cs_Ui_MenuPause) was destroyed, so it didnt subscribe, but the script is still there, what can i do in this situation??

    my apologies if it wasnt clear enough, thanks in advance.