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;
    }
}
相关推荐
游乐码1 小时前
Unity基础(十三)资源卸载
unity·游戏引擎
winlife_1 小时前
全程用 AI 做一款商业级手游 · EP7 表现层与手感:从“能跑“到“摸起来爽“
java·开发语言·人工智能·unity·ai编程·游戏开发·mcp
冰糖橘子ABC1 小时前
Unity 动作重定向
unity·游戏引擎
程序员正茂2 小时前
Unity3d程序发布后自动显示发布日期
unity
晓131312 小时前
【Cocos Creator 2.x】篇——第二章 入门
javascript·游戏引擎
nnsix14 小时前
Unity 贴图压缩格式 笔记
笔记·unity·贴图
ysn111111 天前
搭建状态同步框架的实践心得
unity·架构
一线灵1 天前
Axmol:小众引擎的硬核逆袭
游戏引擎
weixin_441940011 天前
【Unity教程】使用vuforia创建简单的AR实例
unity·游戏引擎·ar
郝学胜-神的一滴1 天前
[简化版 GAMES 101] 计算机图形学 12:可见性与 Z‑Buffer 深度缓存
unity·godot·图形渲染·three.js·opengl·unreal