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;
    }
}
相关推荐
玄米乌龙茶1234 小时前
LLM成长笔记(十三):系统设计与项目实战
笔记·unity·游戏引擎
_Evan_Yao11 小时前
游戏和编程两不误:用Unity做一个简单小游戏
后端·游戏·unity·游戏引擎
2601_9560028112 小时前
钢铁雄心4/Hearts of Iron IV2026官方正版最新版pc免费下载(看到请立即转存 资源随时失效)手机版通用
大数据·游戏·游戏引擎·动画·游戏策划
冰凌糕13 小时前
Unity3D Shader 渲染状态详解
unity
郝学胜-神的一滴13 小时前
[简化版 GAMES 101] 计算机图形学 10:反走样与深度缓冲核心解析
c++·unity·godot·图形渲染·three.js·unreal engine·opengl
技术探讨者1 天前
极境导表工具 —— 让配置数据成为游戏开发的效率引擎
unity·编辑器·ai编程·游戏策划
游乐码1 天前
Unity基础(六)小案例
游戏·unity·游戏引擎
Sator12 天前
Unity2022版接入MCP
unity·ai编程
相信神话20212 天前
第四章:创建《酒魂》项目与场景结构
游戏·游戏引擎·godot·2d游戏开发
mxwin2 天前
Unity Shader URP 使用模板测试 · 深度测试实现秘境空间效果
unity·游戏引擎·shader