我有一个精灵,此刻我检测到鼠标单击它。
但是我真的需要检测手指或鼠标何时触摸或在精灵上移动,因为手指/鼠标单击事件将发生在屏幕上的其他位置,而不是精灵的顶部。
public class Hand : MonoBehaviour
{
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
this.transform.gameObject.SetActive(false);
}
}
}
更新:
我试图同时检测到精灵和鼠标都没有按下,但是我没有单击按钮。我可以删除&& Input.GetMouseButtonDown(0)
,如果鼠标移到上面,它将起作用,但是我希望鼠标/手指都在精灵上并按下。
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000) && Input.GetMouseButtonDown(0))
hit.collider.GetComponent<Button>().onClick.Invoke();
}
答案 0 :(得分:1)
有2种可能的解决方案:
首先:使用按钮并将其分配给世界空间画布,而不仅仅是使用精灵 如果您将canva的事件摄像机分配给主摄像机,则这种情况下的触摸应该起作用。
2nd:如果您只是想使用精灵,则为其分配一个对撞机,并使用raycast
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray,out hit,1000))
hit.collider.gameobject.GetComponent<Button>.onClick().Invoke();
编辑:如果您在Sprite上附加了按钮组件,则上面的代码将起作用。如果不 只是这样叫
if(hit.collider.gameobject.GetComponenet<Sprite>())
DoWhateverYouWant()
答案 1 :(得分:0)
使用EventSystem接口检测与UI元素的任何形式的鼠标交互。
事件系统接口在here中列出。
例如,如果要检测鼠标何时悬停在精灵上,可以将脚本添加到精灵对象中,如下所示:
using UnityEngine.EventSystems;
using UnityEngine;
public class MouseOverHandler: MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public void OnPointerEnter(PointerEventData data){
Debug.Log("MouseEnter");
}
public void OnPointerExit(PointerEventData data){
Debug.Log("MouseExit");
}
}
请注意,EventSystem与关联的精灵的画布上的raycaster一起使用。因此,如果子画面彼此重叠,则它们可以阻止射线广播,因此PointEnter事件仅在最上面的子画面上触发