0

In my first script, I declare an event like so

public static event Action OnChangeScene;

private void OnMouseDown()
{
     OnChangeScene?.Invoke();
}

In my second script, I try to get Destroy(gameObject) to subscribe to that event via a lamda expression.

private void Start()
{
    MoveButton.OnChangeScene += () => Destroy(gameObject);
}

The problem is that it only works the first time the mouse is clicked. After that, I get the error, "MissingReferenceException: The object of type 'Animal' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object."

Sean Carey
  • 799
  • 5
  • 12

1 Answers1

3

You should unsubscribe from the event upon destroying the object.

However, you are subscribing an anonymous method, and you will need a reference to it for unsubscribing it. (more details on this question and that too). You can find official information on MSDN page about the matter.

If you will not have to unsubscribe to an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.

It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event. In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.

Consider this approach:

private Action destroyDelegate;

private void Start()
{
    destroyDelegate = () => Destroy(gameObject);
    MoveButton.OnChangeScene += destroyDelegate;
}

protected void OnDestroy()
{
    MoveButton.OnChangeScene -= destroyDelegate;
}
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36