In this example there are three objects: Player, Laser, and Enemy. Player fires laser at Enemy or Enemy falls on Player.
Script communication in the Inspector
The Laser and Enemy objects are one hit and done. The Player object needs a damage score that decreases to zero and done.
public class Player : MonoBehaviour
{
[SerializeField]
private int _lives = 3;
...
}
Add a Player.Damage() method to allow the outside classes, Enemy, to change the value of variable _lives, a public method.
public class Player : MonoBehaviour
{
...
public void Damage() // capital 'D'
{
_lives -= 1; // _lives --; _lives = _lives - 1;
if(_lives < 1)
{
Destroy(this.gameObject); //destroy Player
}
}
...
}
Transform is the only method to access, directly access other GameObjects. Here are name, tag, and the new Damage() method:
public class Enemy : MonoBehaviour
...
private void OnTriggerEnter(Collider other)
{
//Debug.Log("Hit: " + other.transform.name);
// if (other.transform.name == "Player")
if (other.tag == "Player")
{
other.transform.GetComponent<Player>().Damage();
} // the <Player> in the ‘< >’ is the Player Script component, not the Player GameObject
}
...
}
The <Player> in the ‘< >’ is not the Player class, it is the Player Script component.
Player component of Player gameObject
What when the other gameObject component does not exist? (turned off, removed, or the entire gameObject has been deleted, or ‘Damage’ was never there to begin with)
First check for the component’s existence before calling the outside component.
public class Enemy : MonoBehaviour
{
...
Player player = other.transform.GetComponent();
if(player != null)
{
player.Damage();
// other.transform.GetComponent().Damage();
}
...
}