- Home /
Other
Destroy(gameObject) only works once
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."
Answer by jim3878 · May 27, 2018 at 03:03 AM
you need to unsubscribe event before destroy game object.
Try this
private void Start()
{
MoveButton.OnChangeScene += DestortyGameObject;
}
private DestortyGameObject(){
MoveButton.OnChangeScene -= DestortyGameObject;
Destroy(gameObject);
}
But the whole point of using a lamda expression is so I wouldn't need to create a method.
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.
In my opinion ,to create a method seems rather feasible.
Further more anonymous methods actually do create a seperate method. Just that you can not directly access it. However the underlying generated code does have an actual method implementation with a compiler internal name. Also in this case the lambda expression is a closure. So you actually create a closure object as well