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 :)
elseinstead ofelse if (control != this). Cf. principle of least astonishment. \$\endgroup\$controlis no longernull, and the object containing theGameControlscript would be destroyed. There's a reason it'selse if. \$\endgroup\$Awakeis called once in a script instance's lifetime, not on each scene change. So the firstGameControlinstance would assign itself toGameControl.controlin itsAwakeand any furtherGameControlinstances will destroy themselves in theirAwakes. \$\endgroup\$else. \$\endgroup\$