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;
    }
}
相关推荐
mxwin1 天前
Unity URP 热更新兼容性:Shader 在 IL2CPP 打包下的注意事项
unity·游戏引擎
mxwin1 天前
Unity shader中TransformWorldToShadowCoord原理解析
unity·游戏引擎·shader
mxwin1 天前
Unity Shader 中 ShadowCaster的作用和疑问
unity·游戏引擎
mxwin2 天前
Unity Shader中如何学习阴影技术 产生阴影,接受阴影,联级阴影,软阴影
学习·unity·游戏引擎·shader
♡すぎ♡2 天前
ShaderLab:线条几何体旋转
unity·计算机图形学·着色器·shaderlab
小贺儿开发2 天前
【MediaPipe】Unity3D 指间游鱼互动演示
游戏·unity·人机交互·摄像头·手势识别·互动·康复训练
mxwin2 天前
Unity Shader中CastShadows 和 ReceiveShadows 在代码中的区分
unity·游戏引擎·shader
努力长头发的程序猿2 天前
Unity2D当中的A*寻路算法
算法·unity·c#
RReality2 天前
【Unity Shader URP】Matcap 材质捕捉实战教程
java·ui·unity·游戏引擎·图形渲染·材质
魔士于安2 天前
unity urp材质球大全
游戏·unity·游戏引擎·材质·贴图·模型