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?

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.

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.

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;