I’m working on a shoot em up game. And sometimes when my enemies die the error appears in the console. I Instantiate random enemy prefabs. All with the right tag, every variable is set in the inspector.
The error appears on like 5 - 10% of killed enemies. It was working the whole time.
NullReferenceException: Object reference not set to an instance of an object
EnemyController.TakeDamage (Single damage) (at Assets/Scripts/EnemyController.cs:98)
UnityEngine.Component:SendMessage(String, Object)
Shot:OnTriggerEnter2D(Collider2D) (at Assets/Scripts/Shot.cs:28)
Shot.cs:28+
void OnTriggerEnter2D(Collider2D col)
{
if(col.tag == "player" && this.gameObject.tag == "enemyShot")
{
col.SendMessage("TakeDamage", damage);
Destroy(this.gameObject);
}
if(col.tag == "enemy" && this.gameObject.tag == "playerShot")
{
col.SendMessage("TakeDamage", damage); //28
Destroy(this.gameObject);
}
}
EnemyController.cs
protected void Die()
{
Punktanzeige.SendMessage("AddPoints", ScorePoints);
Instantiate(explosion, this.gameObject.transform.position, this.gameObject.transform.rotation);
this.GetComponent<DropController>().SpawnPowerUp();
speaker.PlayOneShot(destroySound);
Destroy(this.gameObject);
}
protected void TakeDamage(float damage)
{
speaker.PlayOneShot(hitSound); //98
sr.sprite = hitSprite;
nextSprite = Time.time + hitEffectTime;
hp -= damage;
if (hp <= 0)
{
Die();
}
}