Why using Start method in EnemyBehaviour?

In EnemyBehaviour, instead of:

  1. create a private var scoreKeeper;
  2. re-create the Start() method to initialize that var;
  3. call Score() method when health <= 0

we can’t simply use a single line of code, directly in the enemy trigger?

void OnTriggerEnter2D(Collider2D collider){ Projectile missile = collider.gameObject.GetComponent<Projectile>(); if (missile){ health -= missile.GetDamage(); missile.Hit(); if (health <= 0) { GameObject.Find("ScoreText").GetComponent<ScoreKeeper>().Score(scoreValue); // THIS ONE Destroy(gameObject); } } }

edit: I used ScoreText instead of Score for the UI object

You can, but if I understand correctly (although it’s not stated in the lecture - that I noticed), it’s more efficient to only look up the ScoreText object once (at the Start), rather than looking it up each and every time an enemy is destroyed. Bear in mind that this is a small project, so it doesn’t have to look through many objects (relatively speaking) to find the one it wants, but in a larger project…

Privacy & Terms