3
\$\begingroup\$

From proper leak protection do I need to delete both of these or will getting rid of one take care of both?

Currently I am destroying the script AND the gameobject

private void OnDestroy() {
    Destroy(this.gameObject);
    Destroy(this);
}
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't see why you would need this in the first place .. OnDestroy is called anyway when the component already gets destroyed .. so why do you think you have to destroy it again? \$\endgroup\$ – derHugo Aug 18 '18 at 4:56
  • \$\begingroup\$ The rest depends on what you need .. sometimes you only want to remove one component .. something you want to remove the entire GameObject.. \$\endgroup\$ – derHugo Aug 18 '18 at 5:06
12
\$\begingroup\$

You only need to destroy the GameObject.

By destroying the GameObject (Destroy(this.gameObject);), you also destroy the script (Destroy(this)) automatically.

Destroying the script simply removes the component from the GameObject. Destroying the GameObject removes all of its components, and the GameObject itself.

But there is an issue with your code. OnDestroy() is called when the component is being destroyed. (This could be because the component is destroyed, or its GameObject.) So calling the code in there is probably not what you want.

\$\endgroup\$
  • 4
    \$\begingroup\$ This is completely intuitive when seeing that GameObjects don't really do anything and are just "bags of components" with a name and ID. Everything that a GameObject "does" is actually a component doing something. \$\endgroup\$ – Raphael Schmitz Aug 17 '18 at 15:27
  • \$\begingroup\$ It totally depends on the situation ... Sometimes removing only the component is exactly what you want to do.. sometimes you want to destroy the entire object. Your last section is the actual answer for the OP: destroying it again in OnDestroy makes no sense .... \$\endgroup\$ – derHugo Aug 18 '18 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.