首页 > 解决方案 > Unity新输入系统中如何替换OnMouseDown?

问题描述

Unity 有一个新的输入系统,旧的OnMouseDown() {}不再工作。

迁移指南中,他们提到将其替换为Mouse.current.leftButton.isPressed. 在其他论坛帖子中,他们提到使用InputAction. 问题是这些选项检测场景中任何地方的鼠标点击,而不仅仅是对象:

public InputAction clickAction;

void Awake() {
      clickAction.performed += ctx => OnClickedTest();
}

void OnClickedTest(){
      Debug.Log("You clicked anywhere on the screen!");
}

// this doesn't work anymore in the new system
void OnMouseDown(){
      Debug.Log("You clicked on this specific object!");
}

如何使用 Unity 中的新输入系统检测特定游戏对象上的鼠标点击?

标签: unity3d

解决方案


在场景中的某处使用此代码:

using UnityEngine.InputSystem;
using UnityEngine;

public class MouseClicks : MonoBehaviour
{
    [SerializeField]
    private Camera gameCamera; 
    private InputAction click;

    void Awake() 
    {
        click = new InputAction(binding: "<Mouse>/leftButton");
        click.performed += ctx => {
            RaycastHit hit; 
            Vector3 coor = Mouse.current.position.ReadValue();
            if (Physics.Raycast(gameCamera.ScreenPointToRay(coor), out hit)) 
            {
                hit.collider.GetComponent<IClickable>()?.OnClick();
            }
        };
        click.Enable();
    }
}

您可以IClickable为所有想要响应点击的游戏对象添加一个接口:

public interface IClickable
{
    void OnClick();
}

using UnityEngine;

public class ClickableObject : MonoBehaviour, IClickable
{
    public void OnClick() 
    {
        Debug.Log("somebody clicked me");
    }
}

推荐阅读