NullRefrenceExpection.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NormalZombieAttack : MonoBehaviour
{
    public int normalZombieDamage = 10;
    private void OnTriggerEnter2D(Collider2D hitinfo)
    {
        PlayerHealth player = hitinfo.GetComponent<PlayerHealth>(); // try to find a player health script on the object the zombie collided with
        player.TakeDamage(normalZombieDamage); // make the player take the normal amount of damage from a zombie


         
    }
}
public class Bullet : MonoBehaviour
{
    public float speed = 20f; // this is the speed the bullet is traveling at
    public Rigidbody2D rb2d; // stores the rigidbody on this game object
    public int damage = 50; // stores the amount of damage the bullets will do
    // Start is called before the first frame update
    void Start()
    {

        rb2d.velocity = transform.right * -1 * speed; // make the bullet fly forward
    }

    private void OnTriggerEnter2D(Collider2D hitInfo) // store info about the enemy we hit
    {
        NormalZombieHeath zombie = hitInfo.GetComponent<NormalZombieHeath>(); // try to finda health script for a normal zombie on the object we hit
        zombie.TakeDamage(damage); //the zombie takes damage
        Destroy(this.gameObject); // The bullet clone is destroyed
    }
}

On these scripts, I am receiving this error a NullRefrenceExeption: Object reference not set to the instance of an object. Could someone tell me what I should change in this case so these scripts run as expected?

Hi,
Have you checked the manual and done a few web searches for this error?

double click on the error and see what line it’s addressing. Then investigate the reason…

This is THE SINGLE MOST COMMON ERROR. Learn to fix it fast. Here is how:

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

2 Likes

Kurt-Decker I have found the reason, PlayerHealth player = hit info.GetComponent<PlayerHealth>(); // try to find a player health script on the object the zombie collided with but I have yet to find why the player variable is null if I had to take a guess, hitInfo is null, but I could be very wrong, I’m rather new to this.

Thank you everyone who replied to this question! I have fixed the error, in case anyone else runs into my situation, it was due to two different triggers having the same name. Just me being clumsy with names that’s all.

1 Like