Dave
Dave

Reputation: 2842

Problem with event unsubscribing OnDisable

I register events in OnEnable and unregister them in OnDisable. In most cases it works but I have one simple script which is causing the MissingReferenceException: The object of type 'GraphicsSwitch' has been destroyed but you are still trying to access it. when I load a new scene and invoke the event by pressing a button.

I know that the OnDisable is called as I checked with Debug.Log. The event is not invoked in the new scene before I press a button in the new scene.

After adding if (this != null) the error is gone. Checking if the gameObject is null is not working. It seems that the event is not unsubscribed and the method is called on destroyed object from the previous scene.

The code is very simple:

private void OnEnable()
{
    AdjustGraphics();
    GameSettings.GraphicsChanged += AdjustGraphics;
}

private void OnDisable()
{
    GameSettings.GraphicsChanged -= AdjustGraphics;
}

private void AdjustGraphics()
{
    //without this line I get the error
    if (this != null)
        gameObject.SetActive(GameSettings.Graphics >= requiredQuality);
}

Method AdjustGraphics should not be called in the new loaded scene. I thought the objects should be unsubscribed without any delay. Is it something I am missing when it comes to unsubscribing events?

I know objects in Unity are not destroyed right away but the OnDisable is called on time so my script/object should not listen to GameSettings.GraphicsChanged event anymore when new scene is loaded.

Upvotes: 0

Views: 1862

Answers (2)

user19137361
user19137361

Reputation: 1

This link helped me:

https://forum.unity.com/threads/how-to-remove-and-inputaction-phase-callback.894601/

private void doSomething(CallbackContext ctx)
{
// do the thing
}

//register
action.started += doSomething;
//unregsiter
action.started -= doSomething;

Upvotes: 0

Patryk Szylin
Patryk Szylin

Reputation: 72

Correct me if I'm wrong but when you loading a new scene, your objects are destroyed hence the MissingReferenceException unless you use DontDestroyOnLoad.

If you don't want to use it, then make sure to initialize the object at the start of the scene load i.e. make sure your object exists in the scene before calling any of its functions.

Upvotes: -1

Related Questions