简体   繁体   English

为什么事件触发器不能在 unity 2d 中工作?

[英]Why doesn't Event Trigger work in unity 2d?

I have created a UI Button in unity 2d and it works fine.我在 unity 2d 中创建了一个 UI 按钮,它工作正常。 But I think the event trigger component doesn't work.但我认为事件触发器组件不起作用。 I want to make the button bigger when the cursor is on the button and return to normal size when the cursor exits it.我想在光标位于按钮上时使按钮变大,并在光标退出时恢复正常大小。 Here is my script...这是我的脚本...

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()
    {
        
    }
}

When I play the game, the Console says that the cursor has entered and exited当我玩游戏时,控制台说光标已进入和退出

安慰

But the scale of the button never changes.但是按钮的比例永远不会改变。

What is wrong here?这里有什么问题?

You need to add the event system.您需要添加事件系统。 Try like this.像这样尝试。


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

Set your handle mode in scene to canvas mode with the T key of the keyboard.使用键盘的 T 键将场景中的手柄模式设置为画布模式。 Key w,e,r,t are to manipulate position, rotation, scale and canvas respectively.键 w,e,r,t 分别用于操作位置、旋转、缩放和画布。 You will see the blue circles in the corners with which you will be able to set the size.您将看到角落中的蓝色圆圈,您可以使用它来设置大小。

Check making that bigger to get your events triggered.检查使其更大以触发您的事件。 For the button component case, the area of effect is determined by the canvas size.对于按钮组件情况,效果区域由画布大小决定。 This might also be the case.情况也可能如此。

  1. Check if your Button is in a layout - layouts will set the size and overwrite the changes you do in code.检查您的 Button 是否在布局中 - 布局将设置大小并覆盖您在代码中所做的更改。
  2. Button probably uses RectTransform (as it's a UI Element) so you could try setting localScale of that. Button 可能使用RectTransform (因为它是一个 UI 元素),因此您可以尝试设置它的 localScale。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM