1
votes

I have a sprite that acts as a button in the main menu of my game. It has a box collider, and I use OnMouseDown() to register clicks of the button.

I want to make the sprite change when my mouse rolls over the button. I know I can do stuff using the function OnMouseOver() but how do I switch between 2 sprites completely?

3

3 Answers

3
votes

You don’t need to use two sprites and switch between them. Just use an effect like this one:

void OnMouseOver()
{
    transform.GetComponent<SpriteRenderer>().sprite.color = "your new color for clicking effect";
    transform.GetComponent<SpriteRenderer>().sprite.localScale -= new Vector3(0.1f, 0.1f, 0.1f);
}

and get back all this proccess in OnMouseExit. Or, if you still want to change sprite, you can change it like so:

Sprite sprite;
Sprite highlightSprite;

void OnMouseOver()
{
    transform.GetComponent<SpriteRenderer>().sprite = highlightSprite;
}

void OnMouseExit()
{
    transform.GetComponent<SpriteRenderer>().sprite = sprite;
}

and change back in OnMouseExit.

1
votes

put the mouse functions onto an empty parent GameObject, and parent it to all of the sprites you want, then just enable/disable them via the parent

1
votes

Other options:

  • Use worldspace UI button instead (then you can use the built-in spriteswap transition and other button methods : http://docs.unity3d.com/Manual/script-SelectableTransition.html )
  • Add public Sprite variable and assign mouseover sprite to that, then in OnMouseOver() use that sprite image in your button sprite. (and revert back to original sprite on mouse out)
  • Could also use Mecanim animation, OnMouseOver() toggle to another animation (which only has 1 frame)