So, following along with a tutorial about building a grid-based scroll box (like for an RPG inventory) and I am at a total loss about why a simple call to change an Image.sprite turned in to a nightmare of silliness...or maybe I've been staring at it too long and I can't see the solution... Now the videos are nearly one and a half years old, but I've made other types of UI scroll boxes from these tutorials with no issue at all. Only the Image object seems to be the problem. So I came here and found quite a few NULL Image posts but none quite matched this problem. Most had to do with GetComponent which I use in the function that calls this one and it works fine there - yet this function fails with flying colors... Anyway any tips I could get here would help. A lot. Very frustrating stuff. Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SchedulerGridButton : MonoBehaviour { [SerializeField] private SchedulerGridControl SchedulerGrid; // The culprit... public Image iconImg; public void SetImage(Sprite myImage) { // This function is called from another class to set the sprite to change the // UI button image. The image is sent and received as it should be but // iconImg is always NULL. // This proves to me myImage is there because it shows the name of the // myImage Sprite name every time I run it. Debug.Log("MyImage.name = " + myImage.name); /// ...and here is the problem. // the sprite that is supposed to be set here cannot because iconImg is // always NULL. if (iconImg != null) { iconImg.sprite = myImage; } else { Debug.Log("** iconImg == null"); } } }
You need to assign an image to iconImg. You can either do that in the inspector or from another script. If you think you have already done that type t:SchedulerGridButton in the hierarchy search box to check that you don't have an instance of the class on a gameobject you didn't know about.