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;
    }
}
相关推荐
JIes__13 小时前
Unity(二)——核心系统
unity·游戏引擎
独处东汉14 小时前
freertos开发空气检测仪之按键输入事件管理系统设计与实现
人工智能·stm32·单片机·嵌入式硬件·unity
Howrun77714 小时前
虚幻引擎_C++_游戏开始菜单
游戏·游戏引擎·虚幻
速冻鱼Kiel14 小时前
虚幻状态树解析
ue5·游戏引擎·虚幻
天人合一peng17 小时前
Unity 中 Text-TextMeshPro的获取与赋值
unity·游戏引擎
天人合一peng1 天前
Unity中button 和toggle监听事件函数有无参数
前端·unity·游戏引擎
_乐无2 天前
Unity加载gly 点云 高斯泼溅渲染
unity
坚定信念,勇往无前2 天前
unity发布BuildWebGL.wasm 加载过慢
unity·wasm
avi91112 天前
Unity Data Excel读取方法+踩坑记;和WPS Excel的一些命令
unity·游戏引擎·excel·wps·data
郁闷的网纹蟒2 天前
虚幻5---第12部分---蒙太奇
开发语言·c++·ue5·游戏引擎·虚幻