Search Unity

NULL Image problem

Discussion in 'Scripting' started by pharaway, Mar 23, 2019.

  1. pharaway

    pharaway

    Joined:
    Nov 30, 2018
    Posts:
    6
    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):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class SchedulerGridButton : MonoBehaviour
    8. {
    9.  
    10.     [SerializeField]
    11.     private SchedulerGridControl SchedulerGrid;
    12.  
    13.     // The culprit...
    14.     public Image iconImg;
    15.  
    16.     public void SetImage(Sprite myImage)
    17.     {
    18.         // This function is called from another class to set the sprite to change the
    19.         // UI button image. The image is sent and received as it should be but
    20.         // iconImg is always NULL.
    21.  
    22.         // This proves to me myImage is there because it shows the name of the
    23.         // myImage Sprite name every time I run it.
    24.         Debug.Log("MyImage.name = " + myImage.name);
    25.  
    26.         /// ...and here is the problem.
    27.         // the sprite that is supposed to be set here cannot because iconImg is
    28.         // always NULL.
    29.         if (iconImg != null)
    30.         { iconImg.sprite = myImage; }
    31.         else { Debug.Log("** iconImg == null"); }
    32.     }
    33.  
    34. }
    35.  
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    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.
     
    NullReference0 likes this.