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!");
}
Run Code Online (Sandbox Code Playgroud)
如何使用 Unity 中的新输入系统检测特定游戏对象上的鼠标点击?
Kol*_*lja 11
在场景中的某个位置使用此代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以IClickable
向所有想要响应点击的游戏对象添加一个接口:
public interface IClickable
{
void OnClick();
}
Run Code Online (Sandbox Code Playgroud)
和
using UnityEngine;
public class ClickableObject : MonoBehaviour, IClickable
{
public void OnClick()
{
Debug.Log("somebody clicked me");
}
}
Run Code Online (Sandbox Code Playgroud)
小智 3
确保场景中有一个EventSystem
带有 an 的 an以及上有一个or ,然后使用对象上的接口,该对象本身或其子对象上有碰撞器:InputSystemUIInputModule
PhysicsRaycaster
Physics2DRaycaster
Camera
IPointerClickHandler
using UnityEngine;
using UnityEngine.EventSystems;
public class MyClass : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick (PointerEventData eventData)
{
Debug.Log ("clicked");
}
}
Run Code Online (Sandbox Code Playgroud)