使用 Camera.ScreenPointToRay 这一函数,从相机发射一条与鼠标位置对应的射线并与游戏对象进行碰撞检测。

游戏对象需要具有 collider。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObejctMouseSelector : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
PrintTargetInfo(hit);
}
}
}

void PrintTargetInfo(RaycastHit hit)
{
print("Target: " + hit.collider.gameObject.name);
print("Position: " + hit.point);
}
}

稍加更改后可实现以下效果: