How to change between two images on button click
Hello. I searched but didn't find any answer. I basically have 1 button for toggling between music on/off. I also want when the button is pressed to change the image to "music off" image and at the same time disable the music. I tried changing the image from the script but it didn't work.
Answer by Wolfshadow · Aug 23, 2015 at 12:13 AM
I use:
{
public bool Show = true;
public GUITexture checkmark;
public Texture2D trans;
public static int showINT = 1;
public Texture2D checkmark1;
void Update ()
{
if (Show == false)
{
showINT = 0;
}
else
{
showINT = 1;
}
}
void OnMouseDown ()
{
if (Show == true)
{
checkmark.GetComponent<GUITexture>().texture=trans;
Show = false;
Debug.Log ("False");
PlayerPrefs.SetInt("hide",showINT = 0);
}
//you are hidden, do not fear
//do required stuff
else
{
checkmark.GetComponent<GUITexture>().texture=checkmark1;
Show = true;
Debug.Log ("Show");
PlayerPrefs.SetInt("show",showINT = 1);
}
// Great Scott! They've found us!
//do required stuff
}
}
This code changes textures, but I use a transparent and normal texture. That's why it has hide vs. show. Just assign any two textures and a gui texture in the editor.
Answer by RafiXWPT · Aug 22, 2015 at 05:35 PM
You are probably doing something wrong. This is proper way to do it:
public Sprite musicOnImage;
public Sprite musicOffImage;
GameObject yourimage;
void Start() {
yourimage = GameObject.Find("yourimage"); // You can find that refference in any way you want, its just example.
}
void ChangeMusicOnOffImage(bool on)
{
if(on)
yourimage.GetComponent<Image>().sprite = musicOnImage;
else
yourimage.GetComponent<Image>().sprite = musicOffImage;
}
It has to work cus I am using simillar code myself.
Next you have only connect that method with button, or add additional global variable to check if music should be off, idk, its up to you.
Answer by MeeWowGames · Aug 15, 2017 at 07:11 AM
It's a bit surprising this isn't directly supported by Unity's Toggle object, but fortunately there's an easy solution.
After creating your Toggle GameObject, add a new Image GameObject under Toggle/Background/ (next to the Checkmark GameObject it includes by default). Make a public Image variable in your script and link this new image to it, like this:
public Image imageToggle_X;
Then, in your script's init function & in the Toggle's OnValueChanged handler, add this line:
imageToggle_X.gameObject.SetActive(!toggleNotifications.isOn);
That way, the Toggle will always draw the background image, it'll draw the Checkmark Image when it's on, and your own custom Image will draw when it's off.
Enjoy!