检测循环Unity3D中最后一个对象的位置

时间:2019-05-13 14:25:36

标签: c# 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;
    }
}

1 个答案:

答案 0 :(得分:0)

您只需要将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
}