C# Toggle Button with images

i need a better example than found in the docs because i cant understand them.

basically i made 4 images: Music On, Music Off, Sound On, Sound Off

now i want to create 2 toggle buttons;
one for Music,
and one for Sound.

as the toggle button i want an image to show and once clicked it will change the image.

let say for an example Music is on, with an image showing the music is on
and when i click, it the image changes; showing that the music is off

i keep getting errors

what i done so far was, i removed unnecessary code.

/// The Music and Sound
public Texture musicOn;
public Texture musicOff;
public Texture soundOn;
public Texture soundOff;
public bool sound = false;
public bool music = false;

void menuSettings()
{	
    /// Back to Menu
    if (GUI.Button (new Rect((screenWidth - buttonWidth) * 0.7f, screenHeight * 0.84f, buttonWidth * 0.4f, buttonHeight * 0.4f), "" , menu))
    {
        menuFunction = mainMenu;
    }
	
    GUI.Label(new Rect(screenWidth * 0.45f, screenHeight * 0.6f, screenWidth * 0.1f, screenHeight * 0.1f), "Music", white);
	
    music = GUI.Toggle (new Rect(screenWidth * 0.55f, screenHeight * 0.6f, screenWidth * 0.1f, screenHeight * 0.1f), music, musicOn);

and can i used GUI styles with toggle buttons?

Yes you can use a style with toggles. What kind of errors do you have ?

i got no idea what i did but it seem that it working, i had to make a loop every time it is clicked then changing textures everytime

2 Answers

2

Line 19 of the first script, at the GUI.Toggle(…), last parameter of the rect’s constructor, you have screenHeight * 0.1, and 0.1 is a double when the rect is expecting a float. Add a f after it, just like the other numbers.

damn it! didnt see that! thanks lol... now how to i set a GUI style sheet with a toggle button?

Just do this:

  • Create a new GUISkin.
  • Add a public variable of type GUISkin and assign your skin to it.
  • In your skin add a new custom style at the very bottom by incrementing the count
  • Rename the custom style to, for example, “musicbutton”
  • assign your music-on texture to the background image of your “active” state in your style and your music-off texture to the “normal” state

In code you have to tell Unity to use your skin by adding this line at the top of your OnGUI function:

    GUI.skin = myPublicSkinVariable;

To make your toggle use your custom style, just do this:

    music = GUI.Toggle (new Rect( ... ), music, "", "musicbutton");