首页 > 解决方案 > 检测循环 Unity3D 中最后一个对象的位置

问题描述

下面的脚本在 Y 轴上生成 20 个对象,我怎样才能得到这个循环中最后一个对象的 Y 位置?

脚本:

public GameObject[] Bricks;

void SpawnBricks(int numCubes = 20, float startY = 3, float delta = 0.6f, float AngleDis = 3f)
{
    int Rand = Random.Range(0, Bricks.Length);
    for (int i = 0; i < numCubes; ++i)
    {
        var Brick = Instantiate(Bricks[Rand], new Vector3(0, startY - (float)i * delta, 0), Quaternion.identity);
        Brick.transform.parent = gameObject.transform;
    }
}

标签: c#unity3d

解决方案


您只需将声明移到Brick循环外,以便在循环退出后保留在范围内,并保留循环中分配的最后一个值:

public GameObject[] Bricks;

void SpawnBricks(int numCubes = 20, float startY = 3, float delta = 0.6f, float AngleDis = 3f)
{
    GameObject Brick;

    int Rand = Random.Range(0, Bricks.Length);
    for (int i = 0; i < numCubes; ++i)
    {
        Brick = Instantiate(Bricks[Rand], new Vector3(0, startY - (float)i * delta, 0), Quaternion.identity);
        Brick.transform.parent = gameObject.transform;
    }

    // Brick now holds the last object returned from Instantiate in the loop
}

推荐阅读