原理是使用射线方法,但是GUI对象和其他游戏对象获取的方法不同
普通游戏对象
void Update ()
{
if(Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线
RaycastHit hitInfo;
if(Physics.Raycast(ray,out hitInfo))
{
Debug.DrawLine(ray.origin,hitInfo.point);//划出射线,只有在scene视图中才能看到
GameObject gameObj = hitInfo.collider.gameObject;
Debug.Log("click object name is " + gameObj.name);
if(gameObj.tag == "boot")//当射线碰撞目标为boot类型的物品 ,执行拾取操作
{
Debug.Log("pick up!");
}
}
}
}
======================
GUI对象
GUI对象不能用Physics.Raycast,需要用canvas下的GraphicRaycaster
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
this.GetComponent<GraphicRaycaster>().Raycast(eventDataCurrentPosition, results);
if (results.Count>0)
{
Debug.Log(results[0].gameObject.name);
}