Why gameObject instead of 'this'?

using ‘this’ is more meaningful instead of gameobject


if I’m not wrong, “this” is an reference of the script itself and not the GameObject that he’s a component of, so if you use “MusicPlayer.DontDestroyOnLoad(this);” you will be saying to don’t destroy that specific script on load instead of saying that it shouldn’t destroy the GameObject that the script is attached to.


Hi iyasar,

Joao_Dalvi is right: the “this” keyword refers to the script component, while “gameObject” (or “this.gameObject”) refers to the gameObject the script component is attached to.
“gameObject” is also used if you have another component (such as a transform) that you want to find the gameObject of.
For example:
transform.getChild(0) returns the transform of the first child of the gameObject. transform.getChild(0).gameObject returns the the first child of a gameObject.

HOWEVER, according to https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html, “DontDestroyOnLoad” should still work (in Unity 5.x), if I understand correctly (“If the object is a component or game object then its entire transform hierarchy will not be destroyed either.”).




SHOULD work.

1 Like

Privacy & Terms