unity3d 获取点击的对象

本文介绍在Unity中如何针对普通游戏对象和GUI对象进行射线检测。对于普通游戏对象,使用Physics.Raycast方法;而对于GUI对象,则需通过GraphicRaycaster组件实现。文章提供了具体的代码示例。

原理是使用射线方法,但是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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值