GameObject [] in Unity

本文关键字:Unity in GameObject | 更新日期: 2023-09-27 18:31:46

    for (int x = 0; x < mapLength; x++)
    {
        var instantiateMap = new Vector3(x * 2, 0, 1);
        GameObject[] cubeObjectClones = Instantiate(cubeObject, instantiateMap, Quaternion.identity) as GameObject;
        cubeObjectClones[x].transform.parent = transform;
    }

无法隐式转换类型UnityEngine.GameObject' to UnityEngine.GameObject[]'

有人可以解释一下我如何解决此错误吗?

GameObject [] in Unity

这是因为实例化方法返回单个游戏对象。相反,您需要使用循环来生成更多实例并将它们添加到数组中。使用以下代码。

GameObject[] cubeObjectClones = new GameObject[mapLength];
for (int x = 0; x < mapLength; x++)
{
    var instantiateMap = new Vector3(x * 2, 0, 1);
    cubeObjectClones[x] = Instantiate(cubeObject, instantiateMap, Quaternion.identity) as GameObject;
    cubeObjectClones[x].transform.parent = transform;
}