Search Unity

NullReferenceException, but it HAS a reference

Discussion in 'Scripting' started by unity_8I_suMy7c9iU0g, Apr 9, 2021.

  1. unity_8I_suMy7c9iU0g

    unity_8I_suMy7c9iU0g

    Joined:
    May 29, 2020
    Posts:
    26
    Trying to write a code for object to reference an image and change it's sprite, but it says that it has a null exception. Image and sprite are linked and GetComponent is present as well. What is causing the problem?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class testhook : MonoBehaviour
    7. {
    8.     public Image fesh;
    9.     public Sprite tfish;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         fesh = GetComponent<Image>();
    14.         Debug.Log("start");
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.  
    21.         if (Input.GetKey(KeyCode.Space))
    22.         {
    23.             // This is where error happens
    24.             fesh.sprite = tfish;
    25.         }
    26.     }
    27. }
    28.  
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    If you're getting a null error, then it's null. Simple as that.
    Either fesh is null because your GetComponent<Image>() call isn't on the same object that has the Image Component or your sprite is null.
     
    Bunny83 likes this.
  3. unity_8I_suMy7c9iU0g

    unity_8I_suMy7c9iU0g

    Joined:
    May 29, 2020
    Posts:
    26
    That's the thing, image is referenced to an image object, and sprite isn't null
    Here's screenshots https://imgur.com/a/1S3Sx1g
     
  4. unity_8I_suMy7c9iU0g

    unity_8I_suMy7c9iU0g

    Joined:
    May 29, 2020
    Posts:
    26
    Problem solved, turns out GetComponent image was unnecessary and furthermore somehow conflicting with sprite change.
     
  5. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Your problem was as stated before from Brath, your gameObject which used "GetComponent" didnt had a "Image" Component which lead to make your "fesh" variable "null"
     
    Bunny83 likes this.