Hello!
I’m at lecture 106 “Player Life and death” and I’m struggling a bit, I get the NullReferenceException: Object reference not set to an instance of an object after copying this two methods from the Enemy.cs and pasting them into the Player.cs
private void OnTriggerEnter2D(Collider2D other)
{
DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
ProcessHit(damageDealer);
}
private void ProcessHit(DamageDealer damageDealer)
{
health -= damageDealer.GetDamage();
if (health <= 0)
{
Destroy(gameObject);
}
}
and after adding the collider components to the enemy laser and the player, if I try to run the game the very second the enemy shoots the game stops and Unity gives me this error:
NullReferenceException: Object reference not set to an instance of an object
Enemy.ProcessHit (.DamageDealer damageDealer) (at Assets/Scripts/Enemy.cs:75)
Enemy.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Enemy.cs:69)
Here is the entire Enemy.cs code I have
public class Enemy : MonoBehaviour
{
[SerializeField] float health = 100;
[SerializeField] float shotCounter;
[SerializeField] float minTimeBetweenShots = 0.2f;
[SerializeField] float maxTimeBetweenShots = 3F;
[SerializeField] GameObject projectile;
[SerializeField] float projectileSpeed = 10f;
// Use this for initialization
void Start()
{
shotCounter = Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
}
// Update is called once per frame
void Update()
{
CountDownAndShoot();
}
private void CountDownAndShoot()
{
shotCounter -= Time.deltaTime;
if (shotCounter <= 0f)
{
Fire();
shotCounter = Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
}
}
private void Fire()
{
GameObject laser = Instantiate(
projectile,
transform.position,
Quaternion.identity
) as GameObject;
laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -projectileSpeed);
}
private void OnTriggerEnter2D(Collider2D other)
{
DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
ProcessHit(damageDealer);
}
private void ProcessHit(DamageDealer damageDealer)
{
health -= damageDealer.GetDamage();
if (health <= 0)
{
Destroy(gameObject);
}
}
Does anyone know why do I get the error? I’ve tried to look into it and I just don’t get it. I’ve also checked other NullReferenceException threads but I still don’t get how I can fix this.
Thank you in advance!