Search Unity

Change UI-Button Source Image in Code

Discussion in 'UGUI & TextMesh Pro' started by rubiktubik, Sep 27, 2014.

  1. rubiktubik

    rubiktubik

    Joined:
    Sep 27, 2014
    Posts:
    2
    Hi, i need to change the Image in the UI-Button in Code, this is what i have:


    How i change the Image of the Button in Code?

    What i have in Code:
    Code (csharp):
    1.  
    2. var objWithImage = GameObject.Find("11");
    3. //Get Image Component? Or Button?
    4. var image = objWithImage.GetComponent<Image>();
    5. //Change image of object
    6.  
    Could someone help me with this problem?
     
    quangtqag likes this.
  2. Capn_Andy

    Capn_Andy

    Joined:
    Nov 20, 2013
    Posts:
    80
    You're pretty close; I'm not sure the JS but in C#:

    Sprite newSprite = sprite; // <- This is the new sprite
    Image theImage = GameObject.Find("11").GetComponent<Image>();
    theImage.sprite = newSprite;​

    The "Image" class has the ".sprite" property that contains the image data.
     
  3. rubiktubik

    rubiktubik

    Joined:
    Sep 27, 2014
    Posts:
    2
    Thanks that helped!
     
    Vexacoe likes this.
  4. MrGamer167

    MrGamer167

    Joined:
    Aug 9, 2015
    Posts:
    3
    hi,
    Im not sure what im doing wrong but when i use ur same code and im seeing this error: "The type or namespace name `Button' could not be found. Are you missing a using directive or an assembly reference?"

    this is my code

    usingUnityEngine;
    usingSystem.Collections;

    public class Main : MonoBehaviour
    {
    bool mute = false;
    //Button image;
    //Image image;
    //Button image = GameObject.Find("Music on").GetComponent<Button>();
    Image image = GameObject.Find("Music on").GetComponent<Image>();
    public Sprite myFirstImage;
    public Sprite mySecondImage;
    publicvoidmuteMusic()
    {
    if(!mute)
    {
    image.SourceImage = mySecondImage;
    }
    else
    {
    image.SourceImage = myFirstImage;
    }
    }
     
    Last edited: Oct 29, 2015
  5. graiderzs

    graiderzs

    Joined:
    Sep 30, 2015
    Posts:
    1
    Mr.Gamer

    You need to put " using UnityEngine.UI; " at the top of your script, in order to use the UI components, which in your case, the button component.
     
  6. ddogle

    ddogle

    Joined:
    Jun 8, 2017
    Posts:
    16
    Hello,

    i'm new i try add buti get error Assets/Scripts/Player.cs(133,45): error CS1525: Unexpected symbol `<internal>'


    I try use your idea to pause game and change button pause



    void Pause ()
    {


    if (canpause) {


    Sprite newSprite = sprite;
    Image theImage = GameObject.Find("P2").GetComponent<Image>();
    theImage.sprite = newSprite;

    Time.timeScale = 0;
    canpause = false;
    }

    else
    {

    Time.timeScale=1;
    canpause = true;

    }
    }