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;
    }
}
相关推荐
__water4 小时前
【关于unity打包Android失败问题】
android·unity
mascon6 小时前
Unity 编辑器扩展
unity·编辑器·游戏引擎
程序员正茂16 小时前
Unity3d使用MQTT异步连接服务端
mqtt·unity·异步
mxwin17 小时前
在unity shader中,通过pass产生阴影,通过主pass的光照 接收阴影!那么问题来了,是先产生阴影吗?还是先接收阴影,执行顺序是啥呢
数码相机·unity·游戏引擎·shader
小贺儿开发18 小时前
《唐朝诡事录之长安》——盛世马球
人工智能·unity·ai·shader·绘画·影视·互动
蒙双眼看世界1 天前
Unity结合ECharts图表及网页插件EmbeddedBrowser的应用开发
unity·游戏引擎·echarts
郝学胜-神的一滴1 天前
中级OpenGL教程 004:为几何体注入法线灵魂
c++·unity·游戏引擎·godot·图形渲染·opengl·unreal
la_vie_est_belle2 天前
Pygame Studio——用Python自制的一款可视化游戏编辑器
python·游戏·编辑器·游戏引擎·pygame·pyside6·pygame-ce
LF男男3 天前
GameManager.cs
unity
晴夏。3 天前
c++调用lua的方法
c++·游戏引擎·lua·ue