Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

[Solved]Change UI source image?

Discussion in 'Scripting' started by RPP, Nov 11, 2015.

  1. RPP

    RPP

    Joined:
    Nov 11, 2015
    Posts:
    28
    I am currently having problems trying to change the source image of an UI image on a canvas. I am trying to have my code work like this, Button pressed -> load new source image in image -> repeats till last image. This is what i have done. Essentially a health bar out of images.

    Code (CSharp):
    1.  
    2.  
    3. void Start()
    4. {
    5. lifeBar();
    6. }
    7.  
    8. void lifeBar()
    9.     {
    10.         Sprite FULLHP =  Resources.Load <Sprite>("suit_life_meter_2");      //FULL
    11.         Sprite LESSHP = Resources.Load <Sprite>("suit_life_meter_0");    //-1
    12.         Sprite LESSERHP = Resources.Load <Sprite>("suit_life_meter_3");  //-2
    13.         Sprite NOHP = Resources.Load <Sprite>("suit_life_meter_1");         //EMPTY
    14.  
    15.   if(gravSuitLife == 3)
    16.      {
    17.        gameObject.GetComponent<Image>().sprite = FULLHP;
    18.      }
    19.      if(gravSuitLife == 2)
    20.      {
    21.        gameObject.GetComponent<Image>().sprite = LESSHP;
    22.      }
    23.      if(gravSuitLife == 1)
    24.      {
    25.        gameObject.GetComponent<Image>().sprite = LESSERHP;
    26.      }
    27.      if(gravSuitLife == 0)
    28.      {
    29.        gameObject.GetComponent<Image>().sprite = NOHP;
    30.      }
    31.    }
    32.     }
     
    Last edited: Nov 11, 2015
  2. Matt-Roper

    Matt-Roper

    <Of The Graphics> Unity Technologies

    Joined:
    Oct 27, 2015
    Posts:
    106
    Hi RPP, welcome to the forum!

    There's nothing wrong with the script you've posted, what's happening when you play it? Also I wouldn't recommend using Resources.Load every time the method is called, you should only need to reference them once at the start.

    Have you checked the other lifebar images are set to sprite and UI in the project/inspector?
     
    m0untgam3 likes this.
  3. RPP

    RPP

    Joined:
    Nov 11, 2015
    Posts:
    28
    Hi Matt, thanks for replying. Ill keep in mind to move the resources out of the loop. Essentially, i have my player controller script so that when i have my Player jump the suitlife variable will be decremented by 1. Currently i have the suitlife set to 3. However i created a sprite sheet and split the sprites into 4 separate images. Currently i have the in-scene image as full HP. I want to switch the image to the next decremented image if the player jumps. I receive the following Exception in my code.

    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.lifeBar () (at Assets/Scripts/PlayerController.cs:98)
    PlayerController.Start () (at Assets/Scripts/PlayerController.cs:18)

    I'm new to Unity, I am not sure if i need to attach something to an object here? or? I believe this error is related to my player object? Thanks again!

    ALSO, regarding the Sprite/UI topic, I have only 1 image, the sprite sheet, but i broke it up into 4 separate pictures in the same image, if that makes sense ill try and link a picture!

     
    Last edited: Nov 12, 2015
  4. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Being new to Unity, you may not know, but there's a cool little feature. If you double click on the error in Unity, it'll hop straight over to the line of text that is causing the problem in Visual Studio / Monodevelop :).

    So in the future you might find that helpful to nail your problems too, but that type of error states that you're trying to call a script or a component that doesn't exist. From what I'm seeing you may not have a Resources folder. In Assets folder, make sure you place your images in a separate folder called 'Resources', not Images. Anything using the Resources.Load function, is searching for that specific folder. When the game's are built, all the folders mesh into one built engine, so all the normal directories dissappear. The 'Resources' folder is the only one that stays as a regular folder that Unity can access.

    So normally people have their Images/Textures in their regular folders, and anything specifically that needs to be referenced in a Directory (like XML files or certain Images) go in the Assets/Resources folder.

    Hope that helps :).
     
    raconjac likes this.
  5. RPP

    RPP

    Joined:
    Nov 11, 2015
    Posts:
    28
    Okay, i renamed my images folder to Resources, however i still receive the same error. When i double click the error it takes me to line 101. which is below:

    Code (CSharp):
    1. gameObject.GetComponent<Image>().sprite = FULLHP;
    The function is posted on my first post if you want to see the functions entire code.
     
    art092 likes this.
  6. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    In that case it's saying that there is either no Image component, or no FULLHP. I'm assuming it's the Image component. I'd check that there is one attached to the object with the script on it. To do a check to make sure it has the component you can do two things:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. // 1) You can require the component when the script is attached. So when you actually drag and drop the script or add the component onto the object in the Editor, it'll automatically make
    6. //  sure it has an Image component. This to be frank is overkill, but it's handy when you want the Editor to add other things for you too, when you attach a script to a GameObject.
    7. [RequireComponent(typeof(Image))]
    8. public class SomeClass : MonoBehaviour {
    9.  
    10.     public float gravSuitLife;
    11.     Sprite FULLHP, LESSHP, LESSERHP, NOHP;
    12.  
    13.     void Start()
    14.     {
    15.         lifeBar();
    16.  
    17.         FULLHP = Resources.Load<Sprite>("suit_life_meter_2");      //FULL
    18.         LESSHP = Resources.Load<Sprite>("suit_life_meter_0");    //-1
    19.         LESSERHP = Resources.Load<Sprite>("suit_life_meter_3");  //-2
    20.         NOHP = Resources.Load<Sprite>("suit_life_meter_1");         //EMPTY
    21.  
    22.         // Delete this when you know it's working :)
    23.         if(Debug.isDebugBuild)
    24.         {
    25.             Debug.Log("FULLHP = " + FULLHP);
    26.             Debug.Log("LESSHP = " + LESSHP);
    27.             Debug.Log("LESSERHP = " + LESSERHP);
    28.             Debug.Log("NOHP = " + NOHP);
    29.         }
    30.     }
    31.  
    32.     void lifeBar()
    33.     {
    34.         // This is the main thing here. I'm just getting it to log an error if there's no Image component.
    35.         Image image;
    36.         if (!(image = gameObject.GetComponent<Image>()))
    37.             Debug.Log("I have no Image component! Fix meeeeeeeeeeeee");
    38.    
    39.         if (gravSuitLife == 3)
    40.         {
    41.             image.sprite = FULLHP;
    42.         }
    43.         if (gravSuitLife == 2)
    44.         {
    45.             image.sprite = LESSHP;
    46.         }
    47.         if (gravSuitLife == 1)
    48.         {
    49.             image.sprite = LESSERHP;
    50.         }
    51.         if (gravSuitLife == 0)
    52.         {
    53.             image.sprite = NOHP;
    54.         }
    55.     }
    56. }
    Also Resources.Load() tends to be a heavier request than the usual, so I've made them only call for each image once and keep a reference. Just in case you are going to be setting the health bar more than once. Plus then you can make sure they're working okay :).
     
    Last edited: Nov 13, 2015
  7. RPP

    RPP

    Joined:
    Nov 11, 2015
    Posts:
    28
    Thanks for the input, when i get some free time to try what you mentioned out, ill post it below!

    Okay, so i decided i will create a new script called LifeBar in c# below, I then attached the script to the image object i created in the scene. When i compile the scene or run it, the image changes to an empty image, with no source image. This is progress, thanks for the help, i will fiddle with this script more when i get the chance. Cheers.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. [RequireComponent(typeof(Image))]
    6. public class LifeBar : MonoBehaviour {
    7.  
    8.  
    9.    public float gravSuitLife = 3;
    10.    public bool gravity; //sudoGravity to act as playerscripts gravity on/off
    11.    Sprite FULLHP, LESSHP, LESSERHP, NOHP;
    12.  
    13.  
    14.    // Use this for initialization
    15.    void Start()
    16.    {
    17.      FULLHP = Resources.Load <Sprite>("suit_life_meter_2");  //FULL
    18.      LESSHP = Resources.Load <Sprite>("suit_life_meter_0");     //-1
    19.      LESSERHP = Resources.Load <Sprite>("suit_life_meter_3");    //-2
    20.      NOHP = Resources.Load <Sprite>("suit_life_meter_1");  //EMPTY
    21.  
    22.      lifeBar();
    23.    }
    24.    
    25.    // Update is called once per frame
    26.    void Update ()
    27.    {
    28.      gravity = false;
    29.      if(gravSuitLife > 0 && (Input.GetKeyDown(KeyCode.UpArrow)) && gravity == false)
    30.      {
    31.        gravSuitLife--;
    32.        gravity = true;
    33.        return;
    34.      }
    35.    }
    36.  
    37.    //lifebar function to detect sprite loaded in image on canvas in scene
    38.    void lifeBar()
    39.    {  
    40.      Image suitHealth;
    41.      suitHealth = gameObject.GetComponent<Image>();
    42.  
    43.      if(gravSuitLife == 3)
    44.      {
    45.        suitHealth.sprite = FULLHP;
    46.      }
    47.      if(gravSuitLife == 2)
    48.      {
    49.        suitHealth.sprite = LESSHP;
    50.      }
    51.      if(gravSuitLife == 1)
    52.      {
    53.        suitHealth.sprite = LESSERHP;
    54.      }
    55.      if(gravSuitLife == 0)
    56.      {
    57.        suitHealth.sprite = NOHP;
    58.      }
    59.    }
    60.  
    61. }
    62.  
    63.  
     
    Last edited: Nov 13, 2015
    P3ndragonLLC likes this.
  8. RPP

    RPP

    Joined:
    Nov 11, 2015
    Posts:
    28
    Wow, so i SOLVED the problem, after 1 hour of gazing(not reading) just staring... I realized my lifebar(); function was called in start()... I moved it to update() and yah, fixed.... AmateurHour.Destroy(); hue
     
  9. DEMENTOR

    DEMENTOR

    Joined:
    Oct 3, 2015
    Posts:
    1
    gameObject.GetComponent<UnityEngine.UI.Image>().sprite = MyMegaSprite;
     
  10. Matt-Roper

    Matt-Roper

    <Of The Graphics> Unity Technologies

    Joined:
    Oct 27, 2015
    Posts:
    106
    Again, just a heads up, you're re-setting the sprite once per frame from resources, which is bad for performance. I would create a reference at the top of the script and store the sprites, then switch between them.
     
  11. smiller3650

    smiller3650

    Joined:
    Oct 9, 2019
    Posts:
    3
    hey guys I know im four years late but in Unity 2019 you can set the transition on the button image to Sprite Swap and drag the sprite you want into the inspector
     
    Stonkzombie and ppoiuytre1 like this.
  12. EmpireStudios

    EmpireStudios

    Joined:
    Oct 23, 2018
    Posts:
    24
    Can you give an example of this using his script? Thanks!
     
  13. Sanjay112000

    Sanjay112000

    Joined:
    Nov 9, 2020
    Posts:
    10
    It is workinf for me.Thank you
     
  14. Klimkam

    Klimkam

    Joined:
    Apr 6, 2021
    Posts:
    1
    You should probably change the "Texture Type" of your images from "Default" to "Sprite (2D and UI)"
     
  15. leoliuxd

    leoliuxd

    Joined:
    Nov 14, 2021
    Posts:
    1
    I am confused on setting the size of the sprites.
    For example ,the original size of the png file is 400 * 400, but the size of the ui image is 50*50, how to resize the sprites to fit the image
     
  16. Billy123456789872222221

    Billy123456789872222221

    Joined:
    Jul 11, 2023
    Posts:
    3
    If you're trying to make a healthbar, can't you just decrease the length of the healthbar if they take a hit instead of trying to have images for different health statuses? It'd be a lot simpler.
     
    BarriaKarl likes this.