- Home /
Why am I getting a "Object reference not set to an instance of an object"
I am working on a menu, using unity's ui. I have an empty scene, with a Canvas, a Panel and an image (square box). There use to be a lot more but this is all I need to get the error.
Attached to the canvas I have the following script attached:
using UnityEngine;
using UnityEngine.UI;
public class CharacterInventory : MonoBehaviour {
public Image Socket0;
void Awake ()
{
Socket0.sprite = Resources.Load<Sprite>("Sprites/spr-Shield-red");
}
}
The "box" is attached to the script in socket0. The "Red Shield" appears in the box as it should however I am getting :
NullReferenceException: Object reference not set to an instance of an object CharacterInventory.Start () (at Assets/Scripts/CharacterInventory.cs:9)
Anyone have any ideas as to why? Over 800 lines of code boils down to 1 line. I have tried a bunch of things but I keep getting the error and I have no idea why!!
Can anyone tell me what is causing this error, and how to fix it.
Thanks in advance
Richard M.
Is that really the correct script? The error message is saying something about the Start() method, but the above script does not even contain such a method.
When looking for errors it is helpful to post the exact script that is producing the problem and not post something similar that should contain the same error. :)
Answer by KyleRasmusson · Sep 06, 2016 at 06:17 AM
This will happen if you don't actually have something set in for the Object. So you're calling the object to do something, but its not actually there. You need to set the reference in the inspector, which I don't believe you're actually doing. So to get around this error, or at least have it stop throwing out the error, try doing this
void Awake ()
{
if(Socket0 != null)
Socket0.sprite = Resources.Load<Sprite>("Sprites/spr-Shield-red");
else if(Socket0 == null)
Debug.Log("Socket0 Not Found!");
}
This wont actually pop in your Image, but it will stop throwing the error, and it will let you know that your image isn't there.