Home > OS >  Trying to make a button hover when cursor is over it
Trying to make a button hover when cursor is over it

Time:12-12

Image of Unity screen and inspector

So I am trying to make a button larger upon a mouse hover. I wrote the code similar to what I found in a YouTube tutorial but it is not working. I believe I have the button setup correctly in the inspector but it is not working when I hover over the button.

public class Hover : MonoBehaviour
      {
 
     public void PointerEnter()
     {
         transform.localScale = new Vector2(1.5f, 1.5f);
 
     }
 
 
     public void PointerExit()
     {
         transform.localScale = new Vector2(1f, 1f);
     }
         
 
     }

CodePudding user response:

Try to change the methods name to "OnPointerEnter"/"OnPointerExit". Otherwise it could be that the Image would not scale up with the size of object. Therefore get the image reference and scale it directly:

private Image playButton;

public void Start() 
 {
     image = GetComponent<Image>();
 }
public void PointerEnter()
 {
     image.transform.localScale = new Vector2(1.5f, 1.5f);

 }


 public void PointerExit()
 {
     image.transform.localScale = new Vector2(1f, 1f);
 }

CodePudding user response:

I would implement IPointerEnterHandle / IPointerExitHandler like e.g.

public class Hover : MonoBehaviour, IPointerEnterHandle, IPointerExitHandler
{
    public void OnPointerEnter(EventSystems.PointerEventData eventData); 
    {
        transform.localScale = new Vector2(1.5f, 1.5f);
    }
 
    public void OnPointerExit(EventSystems.PointerEventData eventData); 
    {
        transform.localScale = new Vector2(1f, 1f);
    }
}

and don't use the EventTrigger at all.


Alternatively you could also directly inherit and overwrite e.g.

public class HoverButton : Button
{
    public override void OnPointerEnter(PointerEventData eventData)
    {
        base.OnPointerEnter(eventData);
        
        transform.localScale = new Vector2(1.5f, 1.5f);
    }
    
    public override void OnPointerExit(PointerEventData eventData)
    {
        base.OnPointerExit(eventData);
        
        transform.localScale = new Vector2(1f, 1f);
    }
}

Note though: Since the Button has a special Inspector you will not be able to expose any fields to the Inspector unless you implement your own custom editor inheriting from ButtonEditor.

  • Related