【问题标题】:Why doesn't Event Trigger work in unity 2d?为什么事件触发器在统一 2d 中不起作用?
【发布时间】:2023-03-28 08:28:01
【问题描述】:

我在统一 2d 中创建了一个 UI 按钮,它工作正常。但我认为事件触发组件不起作用。当光标在按钮上时,我想使按钮变大,并在光标退出时恢复正常大小。这是我的脚本...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayAgainButton : MonoBehaviour
{
    public void PointerEnter()
    {
        Debug.Log("Enter");
        transform.localScale = new Vector2(1.2f, 1.2f);
    }

    public void PointerExit()
    {
        Debug.Log("Exit");
        transform.localScale = new Vector2(1f, 1f);
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

玩游戏时控制台提示光标进出

但按钮的比例永远不会改变。

这里有什么问题?

【问题讨论】:

  • 其他东西似乎会覆盖比例,例如像 HorizontalLayoutGroup 这样的任何东西都启用了控制子规模

标签: c# unity3d user-interface eventtrigger


【解决方案1】:

您需要添加事件系统。试试这样。


using UnityEngine;
using UnityEngine.EventSystems;

public class ButtonTest : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Enter");
        this.transform.localScale = new Vector2(1.2f, 1.2f);
    }



    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Exit");
        this.transform.localScale = new Vector2(1f, 1f);
       
    }
}       
    
 

【讨论】:

    【解决方案2】:

    使用键盘的 T 键将场景中的手柄模式设置为画布模式。键 w,e,r,t 分别用于操作位置、旋转、缩放和画布。您将在角落看到蓝色圆圈,您可以使用这些圆圈设置大小。

    检查放大以触发您的事件。对于按钮组件情况,效果区域由画布大小决定。也可能是这种情况。

    【讨论】:

      【解决方案3】:
      1. 检查您的 Button 是否在布局中 - 布局将设置大小并覆盖您在代码中所做的更改。
      2. Button 可能使用 RectTransform(因为它是一个 UI 元素),因此您可以尝试设置它的 localScale。

      【讨论】:

        猜你喜欢
        • 2011-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-05
        • 1970-01-01
        • 2016-07-03
        相关资源
        最近更新 更多