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;
    }
}
相关推荐
KhalilRuan1 小时前
Unity-MMORPG内容笔记-其一
unity·游戏引擎
向宇it5 小时前
【unity游戏开发——网络】网络游戏通信方案——强联网游戏(Socket长连接)、 弱联网游戏(HTTP短连接)
网络·http·游戏·unity·c#·编辑器·游戏引擎
qq_1682789510 小时前
Protobuf在游戏开发中的应用:TypeScript + Golang 实践
服务器·golang·游戏引擎
切韵10 天前
Unity编辑器扩展:UI绑定复制工具
ui·unity·编辑器
10 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
深空数字孪生10 天前
2025年小程序地图打车的5大技术革新:实时路况预测与智能调度升级
大数据·人工智能·unity·性能优化·小程序·游戏引擎
RPGMZ10 天前
RPGMZ 游戏引擎如何与lua进行互相调用 初探
开发语言·javascript·游戏引擎·lua·rpgmz
程序猿多布11 天前
Unity Addressable使用之检测更新流程
unity·addressable
Bunny Chen11 天前
Unity中的物理单位是真实的吗?
unity·游戏引擎
benben04411 天前
Unity3D仿星露谷物语开发69之动作声音
游戏·ui·unity·c#·游戏引擎