Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Problem loading sprite via script.

Discussion in 'Editor & General Support' started by RealPpTheBest, Aug 28, 2020.

  1. RealPpTheBest

    RealPpTheBest

    Joined:
    Jan 27, 2019
    Posts:
    64
    I wrote this script, not sure where I went wrong :/

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class Character : MonoBehaviour
    7. {
    8.     public GameObject defAv;
    9.     public Image m_Image;
    10.     public Sprite ajAv;
    11.     public Sprite remyAv;
    12.     public Sprite thebossAv;
    13.     public Sprite xbotAv;
    14.     public Sprite ybotAv;
    15.  
    16.     public Text defTx;
    17.  
    18.     void Start(){
    19.         m_Image = defAv.GetComponent<Image>();
    20.     }
    21.  
    22.     public void Aj(){
    23.         m_Image.sprite = ajAv;
    24.         defTx.text = "Aj";    
    25.     }
    26.  
    27.     public void Remy(){
    28.         m_Image.sprite = remyAv;
    29.         defTx.text = "Revy";    
    30.     }
    31.  
    32.     public void TheBoss(){
    33.         m_Image.sprite = thebossAv;
    34.         defTx.text = "The Boss";    
    35.     }
    36.  
    37.     public void XBot(){
    38.         m_Image.sprite = xbotAv;
    39.         defTx.text = "X-Bot";    
    40.     }
    41.  
    42.     public void YBot(){
    43.         m_Image.sprite = ybotAv;
    44.         defTx.text = "Y-Bot";    
    45.     }
    46. }
    47.  
    I get errors like this:
    NullReferenceException: Object reference not set to an instance of an object
    Character.[Function Name Here]() (at Assets/Scripts/Panels/Menu/Add/Character.cs:[Line no. Here])
     
  2. DiegoDePalacio

    DiegoDePalacio

    Unity Technologies

    Joined:
    Oct 28, 2009
    Posts:
    507
    Hi @RealPpTheBest,

    It looks like you didn't assign any `Image` to your public "m_Image" variable in the inspector window, before executing the code.

    If you're unsure, please share here a screenshot of how the inspector window of this component looks like.


    Good luck with it!