UI Images - Object reference not set to an instance of an object
Hi All,
Well, my initial post got zero responses and as a Unity noob I could really use some help. Essentially, I'm not understanding how variables assigned in the Inspector can turn out to be null at runtime.
I had functionality in a class that updated UI images on a canvas. These UI images were public variables that were assigned in the Inspector. It worked wonderfully, but really belonged in its own separate class; so, I created one and changed the original class to reference this new class to duplicate the functionality. However, once I separated it all out, I began getting the above object reference error.
My script bombs out on the following line:
ScoreboardSlots [i + LeadingBlanks] = Instantiate (Digit0, Digit0.transform.parent);
ScoreboardSlots[whatever] is null, which is probably ok at this point because I'm trying to assign it to something. But, Digit0 is also somehow null even though it's been assigned in the editor as a public variable.
Surely I'm missing something very simple but I'm at a loss. Any advice???
Thanks, Todd
Answer by vanfriscia · Feb 09, 2018 at 05:45 PM
Well I never did solve this, but I did implement a workaround. Instead of assigning my UI images in the Inspector via public variables, I changed them to private and created a new public method to initialize them like in the following example:
Digit0 = GameObject.Find ("Digit0").GetComponent<Image> ();
This apparently HAS to be in its own method and called from another script; initially I tried putting it in Start() or Awake(), and while it didn't error out, the variables were again null once other methods were called. I still don't get it but maybe this will be helpful to someone, someday!
Thank you so much, this is exactly what I needed. I have no idea why GetComponent and dragging the image in to reference it was breaking it but this works. Very new to Unity so this was infuriating as I had no idea why the reference was disappearing when I pressed play haha.
I can relate to the fury my friend! But I'm glad to know that this post ended up helping SO$$anonymous$$EBODY even if it didn't help me :). Good luck!