unity获取所有子物体位置,再把获取到的位置重新随机分配给子物体(不含父物体)

unity获取所有子物体位置,再把获取到的位置重新随机分配给子物体(不含父物体)

csharp 复制代码
/// <summary>
/// 给所有子物体随机分配位置
/// </summary>
void RandomLocation()
{
    // 获取当前物体下的所有子物体
    Transform[] childTransforms = GetComponentsInChildren<Transform>(true);

    // 获取子物体位置并保存到列表
    Vector3[] childPositions = new Vector3[childTransforms.Length - 1];
    for (int i = 1; i < childTransforms.Length; i++)//排除自身物体
    {
        childPositions[i - 1] = childTransforms[i].localPosition;
    }

    // 随机分配位置
    Shuffle(childPositions);

     将位置分配给子物体
    for (int i = 0; i < childPositions.Length; i++)
    {
        transform.GetChild(i).localPosition = childPositions[i];
    }
}
/// <summary>
/// 随机分配位置
/// </summary>
void Shuffle(Vector3[] array)
{
    // Fisher-Yates 洗牌算法
    for (int i = array.Length - 1; i > 0; i--)
    {
        int j = Random.Range(0, i + 1);
        Vector3 temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
相关推荐
点心的游戏开发世界6 小时前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
点心的游戏开发世界8 小时前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
郝学胜-神的一滴21 小时前
CMake 047:解锁安装阶段自定义操作,告别配置阶段提前执行坑
运维·服务器·c++·游戏引擎·图形渲染·opengl
微三云生态系统架构师-彭丹2 天前
任务卷轴积分系统架构设计:从任务状态机到合规风控的完整实现
unity·系统架构·游戏引擎
XR技术研习社2 天前
从 PICO 文档看未来短期内的 Unity 版本选择
unity·游戏引擎·xr·vr
玖玥拾2 天前
Unity 热更新(一)
unity·游戏引擎
软件黑马王子2 天前
1.non-MonoBehaviour 单例模式泛型基类
unity·前端框架·c#
KhalilRuan2 天前
Unity性能优化
unity·性能优化·游戏引擎
ellis19702 天前
u3d IMGUI[二] 编辑器扩展
unity
五仁烧饼3 天前
Unity性能优化系列内存篇 - 移动端内存优化
unity·性能优化·游戏引擎