I'm viewing tutorial of Unity. In this tutorial, I see this piece of code:
public class GameControl : MonoBehaviour {
public static GameControl control;
public void Awake() {
if (control == null) {
DontDestroyOnLoad(gameObject);
control = this;
} else if (control != this) {
Destroy(gameObject);
}
}
}
I don't understand above code very much. I just understand the first if. it means: when we first use this class, we will initialize control object and set attribute dontdestroyonload
for this. But I don't understand second if, when will it meet condition control != this
?
Thanks :)
else
instead ofelse if (control != this)
. Cf. principle of least astonishment. \$\endgroup\$control
is no longernull
, and the object containing theGameControl
script would be destroyed. There's a reason it'selse if
. \$\endgroup\$Awake
is called once in a script instance's lifetime, not on each scene change. So the firstGameControl
instance would assign itself toGameControl.control
in itsAwake
and any furtherGameControl
instances will destroy themselves in theirAwake
s. \$\endgroup\$else
. \$\endgroup\$