Reputation: 167
Hello I'm new to Unity and I'm trying to make a UI button change its Source Image when the mouse is over it, and when the mouse is no longer over the button, the button's Source Image is back to normal. I know that a sprite is needed to be the button's source image, so I created two image sprite files (one being the normal image and the other being the light-up image when the mouse hovers over the button)
Now here is a screenshot of the play button having its normal source image
Button will change its source image by lighting up when mouse goes over it
How do I do this task in C#? How do I change the source image of the button in C# when the mouse hovers over it?
This is what I got so far after looking at some references. I'm new to Unity so sorry for my lack of knowledge
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayButton : MonoBehaviour {
private PlayButton pb;
private Sprite newSprite;
// Use this for initialization
void Start () {
pb = GetComponentInChildren<PlayButton> ();
}
// Update is called once per frame
void Update () {
}
public void onClick(){
}
public void onPointerHover(PointerEventData eventData){
//When mouse hovers over the button, the button changes
pb.image.overrideSprite = newSprite;
}
}
Upvotes: 2
Views: 9348
Reputation: 125315
There is no such thing as onPointerHover
. To detect mouse over use OnPointerEnter
. To detect when the mouse exist from the mouse over, use OnPointerExit
. You have to implement IPointerExitHandler
and IPointerEnterHandler
in order to use these functions.
You read more examples here.
As for changing the source Image of the Button, Button.image.sprite
or Button.image.overrideSprite
can be used to do that.
Just attach this the Button Object:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class PlayButton : MonoBehaviour, IPointerExitHandler, IPointerEnterHandler
{
private Button pb;
public Sprite newSprite;
void Start()
{
pb = GetComponent<Button>();
}
public void OnPointerEnter(PointerEventData eventData)
{
pb.image.sprite = newSprite; ;
Debug.Log("Mouse Enter");
}
public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("Mouse Exit");
//Change Image back to default?
}
}
EDIT:
Note that you don't have to do this yourself. Unity has built in way to do it.
1.Change the Button's Transition option from "Color Tint" to "Sprite Swap".
2.Change the "Highlighted Sprite" slot to which ever Sprite you want.
Upvotes: 9