- Home /
What's the easiest way to make a texture button with a hover state?
The UI elements in Unity are doing my head in. I want a 2D texture button to change to a different texture when hovered over with the mouse but this seems complicated.
The positioning using rect is way more confusing than positioning a GUITexture object, and swapping texture seems to require a GUIstyle. Is this the best way?
Answer by ShadyProductions · Jul 21, 2014 at 07:17 PM
Try something like
var normalGUI : Texture2D; // change this on inspector
var hoverGUI : Texture2D; //change this on inspector
function OnMouseEnter() {
guiTexture.texture = hoverGUI;
}
function OnMouseExit() {
guiTexture.texture = normalGUI;
}
function OnMouseDown() {
//do something when clicked on the button
}
Although, GUI's can't be assigned to objects I think, they are only on screen.
Thanks! Not the most ideal solution as it means every GUI element has to have its own script. I'll have to live with that though!
Answer by Tony_T · Jul 21, 2014 at 04:35 PM
I'm atually using a quad with the texture of a button. Then i just use OnMouseEnter() and OnMouseExit() to change the material. Not sure if that's what you want.
I know what you mean, I've been using that method so far. But the issue is that the image looks stretched because it's not pixel-perfect, which is why I wanted to use the GUI texture.
Answer by robertbu · Jul 22, 2014 at 02:39 AM
Here is a solution that stumbled on. I'm giving it to you with some caviots. First I could not find documentation for it anywhere. I use EZGUI for my interface work, so I don't have much depth with GUI. But in looking at the reference and many UA questions, I did not see it used. So there may be issues, and/or it may work today and not work in some future build. Second, it appears to make a permanent change to the project. Run once, you can disable the script and the hover still works. I don't know what would happen if you switched platforms, or if doing a build will pull the texture in without a reference.
#pragma strict
var hoverTexture : Texture;
private var init = false;
function OnGUI() {
if (!init) {
GUI.skin.button.hover.background = hoverTexture;
init = true;
}
}
Put this on one game object and it changes the hover texture everywhere. If you want to return to the default texture you, set the texture to null;
GUI.skin.button.hover.background = hoverTexture;
Your answer
Follow this Question
Related Questions
guitexture to act as a button on the keyboard or mouse 0 Answers
How-to-make-GUI-Buttons-on-GUI-Texture-resolution-independent 0 Answers
GUI Button text color not changing on hover 2 Answers
Reduce Draw call for Multiple GUI Textures with same Texture 1 Answer
Transferring Color from script on another GameObject to a GUI.Box 1 Answer