x


Is there a way to create a simple rollover button?

Hi,

I want to have a simple button that acts like this: I have a Normal State texture, and a Mouse Over Texture. I want the button to rollover when the mouse is over it.

Is there a way to detect if the mouse is over the button and then change the texture? Is this possible with UnityGUI or the only option would be to create the interface in 3D?

Thanks,

more ▼

asked Dec 05 '09 at 02:57 PM

hector78 gravatar image

hector78
46 2 2 5

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

You cannot detect directly if the mouse is over a texture, but you can check if it's inside its rectangle. Here's an example:

var normalTexture : Texture2D;
var overTexture : Texture2D;

private var correctedMousePosition : Vector2;

function OnGUI ()
{
    correctedMousePosition = Vector2 (Input.mousePosition.x, (Screen.height-Input.mousePosition.y) );
    if ( Rect(10,10,200,50).Contains(correctedMousePosition) )
    {
    	GUI.DrawTexture( Rect(10,10,200,50) , overTexture);
    	if( Input.GetMouseButtonUp(0) )
    	{
    		Debug.Log("The button has been pressed");
    	}
    }
    else
    {
    	GUI.DrawTexture( Rect(10,10,200,50) , normalTexture);
    }
}
more ▼

answered Dec 05 '09 at 11:34 PM

hector78 gravatar image

hector78
46 2 2 5

(comments are locked)
10|3000 characters needed characters left

UnityGUI supports mouse rollover by default. There are lots of examples in the docs.

This example will react to rollover and click (from the OnGUI script reference):

function OnGUI () {
    if (GUI.Button (Rect (10,10,150,100), "I am a button")) {
        print ("You clicked the button!");
    }
}

To answer the first part of your question, search the script reference for "mouse" and you should find all kinds of functions for getting the mouse state. Then based on whatever state you're in, your script could use thisTexture.enabled = true and thatTexture.enabled = false to switch visibility of 2 different textures on rollover (for example).

more ▼

answered Dec 05 '09 at 03:34 PM

rocket5tim gravatar image

rocket5tim
859 12 17 33

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2277
x1001

asked: Dec 05 '09 at 02:57 PM

Seen: 2806 times

Last Updated: May 29 '11 at 06:59 PM