Object reference not set to an instance of an object

Mission: Junior Programming

Project: Unit 2 - Basic Gameplay

Tutorial: Bonus Features 2 - Share your Work

Hi there, I’m working my way through the different tutorials of the Junior Programming pathway. However, I’ve got stuck with the final feature from the bonus features of the second challenge, which consists of adding a health bar to all the spawning animals so that you can know how much more food you need to feed them to make them disappear.

After hours of googling I wasn’t getting anywhere near to implementing the feature, so I decided to use the step-by-step solutions pdf to be able to achieve it. Nevertheless, after following all the instructions (which you can see in the document attached below) and trying to run the game, I got the following exception:

NullReferenceException: Object reference not set to an instance of an object
DetectCollisions.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/DetectCollisions.cs:32)

The line of code causing the exception is:
other.GetComponent().FeedAnimal(1);

I have no idea why this can be happening as I haven’t worked with Unity that long. Can anyone help me?

These are the two C# files involved in this exception:

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

public class AnimalHunger : MonoBehaviour
{
    // Variables
    public Slider hungerSlider;
    public int amountToBeFed;
    private int currentFedAmount = 0;
    private GameManager gameManager;

    // Start is called before the first frame update
    void Start()
    {
        hungerSlider.maxValue = amountToBeFed;
        hungerSlider.value = 0;
        hungerSlider.fillRect.gameObject.SetActive(false);
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();  
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    public void FeedAnimal(int amount)
    {
        currentFedAmount += amount;
        hungerSlider.fillRect.gameObject.SetActive(true);
        hungerSlider.value = currentFedAmount;
        if(currentFedAmount >= amountToBeFed){
            gameManager.AddScore(amountToBeFed);
            Destroy(gameObject, 0.1f);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectCollisions : MonoBehaviour
{
    // Variables
    private GameManager gameManager;

    // Start is called before the first frame update
    void Start()
    {
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    // Destroy objects on collision event
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player")){
            gameManager.RestLives(1);
            Destroy(gameObject);
        }
        else {
            //gameManager.AddScore(1);
            //Destroy(other.gameObject);
            other.GetComponent<AnimalHunger>().FeedAnimal(1);
            Destroy(gameObject);
        }   
    }
}

8189286–1067313–Unit 2 - Bonus Features Solutions.pdf (3.42 MB)

It does surprise me that this is the most common problem reported on the forums given that it’s a basic thing about the C# language i.e. the difference between value-types and reference-types.

Note that this isn’t a Unity thing. It’s a C# reference type that’s NULL (not referring to anything) but then you’re trying to use it. The error tells you the line so you have to figure out why it’s NULL. Often it’s getting a component then using the component but if a component isn’t found, it’ll return NULL i…e you’re assuming the component will be found. In your head it should be but the component obviously isn’t there in reality.

Anyway, there’s a post about it here: https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

2 Likes

“following instructions” is the bare minimum.

Now it’s time to do the ONLY three steps that will ever fix this issue.

Welcome to debugging!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

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

Every minute you do something that is NOT the above three steps is a wasted minute.

1 Like

I also got trapped in this issue so I’ll comment for future reference.
In this particular case you always have to remember to set the Slider in the hungerSlider field, dragging and dropping it in the animal prefab, you also should do the same for all the animals you spawn that have the “AnimalHunger” script attached.
I noticed an issue on the PDF tho, i think you should remove “Destroy(gameObject);” in the method OnCollisionEnter in the DetectCollisions script or your animals will be destroyed by the first piece of food that collides with them rending the FeedAnimal() method unused.

//Check if the other tag was an Animal, if so add points to the score
else if (other.CompareTag(“Animal”))
{
other.GetComponent().FeedAnimal(1);
//Destroy(gameObject);
}

AnimalHunger.cs keep void FeedAnimal as public so that allow you in other cs parameter.