Skip to main content

鼠标点中的物体

3D中 获取鼠标点中的物体

if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
print(hit.transform.name); //打印选中物体的名字
}
}

2D中 获取鼠标点中的物体

2d物体要加 Box Collider 2D 和 Rigidbody 2D

if (Input.GetMouseButtonDown(0))
{
//2d检测 鼠标下的物体
Ray myRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(myRay);
RaycastHit2D hit = Physics2D.Raycast(new Vector2(myRay.origin.x, myRay.origin.y), Vector2.down);
Debug.Log(hit);
Debug.Log(hit.collider);
if (hit.collider)
{
//do something print (hit.collider);
Debug.Log("2d物体名称:" + hit.collider.name);
}
}