unity3d - 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 中的新输入系统检测特定游戏对象上的鼠标点击?
解决方案
在场景中的某处使用此代码:
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");
}
}
推荐阅读
- python - 在每个 .py 中导入一个函数
- reactjs - React-Navigation + React-Redux:如何为导航器连接全局容器
- mainframe - PSP(Rocket Software 产品)如何提高 Mainframe 作业的性能
- javascript - reactjs中如何在一个根中使用n模型?
- sql - SQL Server在目标不匹配时合并多个插入
- c# - 如何使用 MigraDoc + PDFsharp 制作带有文本的正方形
- python - 如何修复 ZigZag 问题中的“列表索引超出范围”错误?
- ruta - CLAMP 无法运行 Ruta 规则来预测关系
- php - 如何在 Laravel 的关系查询中使用 distinct
- floating-point - 为单精度正确舍入三角函数