Null Reference Exception?

Hello!

Another user wrote me this script but I keep getting null error with it. Can anyone help me fix this? The error is line 10, fill image. I have been trying to fix it myself but I have not really coded before and I am running low on time. The script is meant to connect a game object (a thick black line) to another game object (an object that fills). The black line object is a child of the fill object. Basically, its a thermometer and I wanted the thick black line to make it clear how full the thermometer is.

using UnityEngine;
using UnityEngine.UI;
public class MoveableLine : MonoBehaviour
{
     private Image fillImage;
     private float rectHeight;
     private float incrementFactor;
     void Update ()
     {
         var fillImageRect = fillImage.GetComponent<RectTransform>();
         rectHeight = fillImageRect.rect.height/2;
         incrementFactor = (fillImage.fillAmount * (fillImageRect.rect.height))- fillImageRect.rect.height/2;
         this.GetComponent<RectTransform>().localPosition=new Vector3(0, incrementFactor, 0);
     }
}

Thanks!

Null errors are simple to fix.

Find out what is null.
Find out why it’s null.

Use Debug.Log if you need to to see what is the value of variables or the Visual Studios debugger.

But, simple answer. fillImage is null. So either you weren’t given the entire script or you didn’t copy it correctly. Either way, you need to assign a value to fillImage.

1 Like

Please include the entire error message when making a post. It includes useful information, such as which line the error is on.

How are you assigning a value to “fillImage”? If you are not, then that would be the problem.

Thanks for the feedback. The error code was NullReferenceException: Object reference not set to an instance of an object. It is in reference to line 10, “fillimage”
This is the entire script, I was not missing anything. I know fill image is null/does not have a value. Where I am confused is how to assign it a value. A lot of the videos I have been watching to try and figure out how to do this in my case have just said I need to assign it a value, which assumes a lot of coding knowledge on my part :stuck_out_tongue:
I tried copy and pasting and editing a few examples from tutorials but most of them just then gave me a different error code. I am really confused as to what type of information I am even supposed to be adding to it.
Sorry for my noobness!

I really suggest you look at tutorials and actually see what they are doing with variables.
The easy answer is just to make it public or add a SerializeField to it. You should easily be able to find this in many tutorials being done. Then you can drag and drop your GameObject with the image component into the variable. Again, many tutorials show this very thing being done.

That should get you there without having to deal with much coding.