unity将选中的预制体对齐到下方任意物体表面
2025-04-08 本文已影响0人
Rayson
using UnityEngine;
using UnityEditor;
public class AlignToSurface : MonoBehaviour
{
[MenuItem("Tools/将选中的预制体贴合表面")]
static void AlignSelectedObjectsToSurface()
{
foreach (GameObject obj in Selection.gameObjects)
{
Vector3 origin = obj.transform.position + Vector3.up * 100f; // 向上偏移,确保从上往下检测
Ray ray = new Ray(origin, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000f))
{
// 对齐到碰撞点
Vector3 newPos = hit.point;
// 如果你希望物体底部落地而不是中心,可以加上模型高度的一半(比如通过 Renderer.bounds)
Renderer renderer = obj.GetComponentInChildren<Renderer>();
if (renderer != null)
{
float bottomOffset = obj.transform.position.y - renderer.bounds.min.y;
newPos.y += bottomOffset;
}
obj.transform.position = newPos;
Debug.Log($"{obj.name} 已贴合表面:{hit.collider.name}");
}
else
{
Debug.LogWarning($"{obj.name} 下方未检测到物体表面");
}
}
}
}
在场景中选择一个或多个悬空的预制体。
在 Unity 菜单栏点击:
Tools > 将选中的物体落地