Destroy GameObject from UnityEvent

Hi,

I want to destroy a GameObject as a response to a UnityEvent and I want to set this up in the editor.

To destroy a GameObject, you call Object.Destroy(GameObject go). Since this a static method, you cannot call it as a response to a UnityEvent. Instead, you need to create custom MonoBehaviour like this

public class DestroyUtil : MonoBehaviour
{
    public void Destroy()
    {
        Destroy(gameObject);
    }
}

or you can create a utility ScriptableObject and use that

[CreateAssetMenu(menuName = "Util/Destruction Util")]
public class DestructionUtil: ScriptableObject
{
    public void Destroy(GameObject gameObject)
    {
        Object.Destroy(gameObject);
    }
}

This all seems very manual for something so mundane. I was wondering, if for all those years, I just wasn’t aware of a more elegant solution to achieve this. Anyone? Thanks!

yeah you got it right, if you want to use UnityEvents you have to make yourself a little library of all the usefull APIs.

1 Like