Script Communication in Unity using GetComponent

Damage to Player by Enemy Collison.

GetComponent

Communicating across scripts using GetComponent, is a good practice and necessary for security.

// Player Method for Damage
public void Damage()
{ _lives -= 1;
//Check if dead
if (_lives <1)
{Destroy(this.gameObject);}
}
// Enemy colliding with Player
private void OnTriggerEnter(Collider other)
{ if (other.tag == "Player"){
// call method from player
Player player = other.transform.GetComponent<Player>();
if (player != null)
{player.Damage();}
Destroy(this.gameObject);
}

PUBLIC VOID is necessary to communicate to other scripts

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store