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;
    }
}
相关推荐
我的offer在哪里17 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
淡海水20 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景20 小时前
4.6 显存和缓存
unity
Zik----1 天前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景1 天前
4.5 顶点和片元
unity
在路上看风景2 天前
31. Unity 异步加载的底层细节
unity
天人合一peng2 天前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂2 天前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的2 天前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y2 天前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表