Unity 点击物体位置获取点击位置贴图像素
时间: 2024-05-08 09:17:54 浏览: 278
要获取点击位置的贴图像素,可以使用以下代码:
```csharp
using UnityEngine;
public class ClickPosition : MonoBehaviour
{
public Texture2D texture; // 要获取像素的贴图
private RaycastHit hit;
void Update()
{
if (Input.GetMouseButtonDown(0)) // 当鼠标左键点击时
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) // 发射射线检测物体
{
Vector2 pixelUV = hit.textureCoord; // 获取点击位置的贴图UV坐标
pixelUV.x *= texture.width;
pixelUV.y *= texture.height;
Color pixelColor = texture.GetPixel((int)pixelUV.x, (int)pixelUV.y); // 获取像素颜色
Debug.Log("Clicked pixel color: " + pixelColor);
}
}
}
}
```
这段代码会在鼠标左键点击时发射一条射线,检测是否点击到物体。如果检测到了物体,就会获取点击位置的贴图UV坐标,然后将其转换为像素坐标,并获取该像素的颜色。最后,代码会将像素颜色打印到控制台中。
请注意,要使此代码正常工作,需要将贴图设置为可读写,并将其类型设置为“Advanced”。可以在 Unity 编辑器中选择贴图,然后在 Inspector 窗口中进行设置。
阅读全文
相关推荐


















