Object not set as an intance of an object. Line 26 and 31

Hi I am new to unity and I have been stuck on this code for a while. I dont understand what causes the errors, there is a shouldFadeToBlack button and a shouldFadeFromBlack button.

But the I push shouldFadeToBlack this error comes up:
NullReferenceException: Object reference not set to an instance of an object
UIFade.Update () (at Assets/Scripts/UIFade.cs:26)

and when I push shouldFadeFromBlack this comes up:
NullReferenceException: Object reference not set to an instance of an object
UIFade.Update () (at Assets/Scripts/UIFade.cs:31)

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

public class UIFade : MonoBehaviour
{

    public Image fadescreen;
    public float fadeSpeed;

    public bool shouldFadeToBlack;
    public bool shouldFadeFromBlack;

    // Start is called before the first frame update
    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
        if(shouldFadeToBlack)
        {
            fadescreen.color = new Color(fadescreen.color.r, fadescreen.color.g, fadescreen.color.b, Mathf.MoveTowards(fadescreen.color.a, 1f, fadeSpeed * Time.deltaTime));
        }

        if(shouldFadeFromBlack)
        {
             fadescreen.color = new Color(fadescreen.color.r, fadescreen.color.g, fadescreen.color.b, Mathf.MoveTowards(fadescreen.color.a, 1f, fadeSpeed * Time.deltaTime));
        }
    }
}

Thanks for your help :slight_smile:

Check out the reference of fadescreen image in inspector

2 Likes

Thanks it worked! Cull Transparent Mes was off

Glad you’re up and running again, but remember: The answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

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.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

1 Like