So, in my Player.cs file I have the following variable
public int score;
Now, on the Enemy.cs file (that handles the enemy behavior), I want to change the Player.cs’ score variable depending on the condition.
Here’s the Enemy.cs code:
public Player MyPlayer;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "PlayerShield")
{
MyPlayer.score++;
destroyEnemy();
}
else if (other.tag == "Player")
{
MyPlayer.life -= 1;
MyPlayer.score += 1;
destroyEnemy();
}
}
private void destroyEnemy()
{
Instantiate(_explosionAnimation, transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
The problem is that, whenever a colision happens, I get the following error that points to the lines where I tried to call the Player.cs’ variable(s):
NullReferenceException: Object reference not set to an instance of an object