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;
    }
}
相关推荐
狂人开飞机3 小时前
14、游戏手感与视觉打磨
游戏·游戏引擎·godot
狂人开飞机8 小时前
15、音频系统
游戏引擎·godot
狂人开飞机9 小时前
16、粒子线条与视觉特效
游戏引擎·godot
心前阳光20 小时前
Unity发布PC软件图标不能改变
unity·游戏引擎
an86950011 天前
unity如何在visual studio中打断点debug
unity·游戏引擎·visual studio
xcLeigh1 天前
Unity基础:使用Transform控制物体移动——Translate与position详解
unity·游戏引擎
FairGuard手游加固1 天前
Unity小游戏加密:global-metadata.dat与AssetBundle保护
游戏·unity·游戏引擎
狂人开飞机1 天前
11、UI系统
游戏引擎·godot
真鬼1231 天前
【Unity AI】Untiy链接cursor与MCP
unity·游戏引擎
WarPigs1 天前
Unity设置人物位置无效的原因
unity