unity3d 试图在光标位于按钮上时使其悬停

r1zhe5dt  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(228)

Image of Unity screen and inspector
所以我尝试在鼠标悬停时使按钮变大。我编写的代码类似于我在YouTube教程中找到的代码,但它不起作用。我相信我在检查器中正确设置了按钮,但当我悬停在按钮上时它不起作用。

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

mu0hgdu01#

尝试将方法名称更改为“OnPointerEnter”/“OnPointerExit”。否则,图像可能不会随对象的大小而缩放。因此,请获取图像引用并直接缩放它:

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);
 }
ujv3wf0j

ujv3wf0j2#

我会实现IPointerEnterHandle/IPointerExitHandler,例如:

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);
    }
}

并且根本不使用EventTrigger
或者,您也可以直接继承和覆盖,例如:

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);
    }
}
  • 请注意:由于Button有一个特殊的检查器,您将无法向检查器公开任何字段,除非您实现自己的自定义编辑器继承自ButtonEditor。*

相关问题