C#/ Unity将实例化的游戏对象添加到数组

时间:2019-03-17 20:58:17

标签: c# unity3d

我目前有一个脚本,可以将预制件放到我的地形上。 这是我执行此操作的代码:

RaycastHit hit;

for (int i = 0; i < spawnerData.spawnableObjects.Length; i++)
{
    if (spawnerData.spawnableObjects[i].currentObjects != spawnerData.spawnableObjects[i].numberOfObjects)
    {
        if (Physics.Raycast(new Vector3(randomX, r.bounds.max.y + 5f, randomZ), -Vector3.up, out hit))
        {
            randomX = Random.Range(r.bounds.min.x, r.bounds.max.x);
            randomZ = Random.Range(r.bounds.min.z, r.bounds.max.z);

            if (hit.point.y >= spawnerData.spawnableObjects[i].spawnerStartHeight && hit.point.y <= spawnerData.spawnableObjects[i].spawnerEndHeight)
            {
                spawnedObject = Instantiate(spawnerData.spawnableObjects[i].spawnablePrefab, hit.point, Quaternion.identity);
                objectsSpawned[spawnerData.spawnableObjects[i].currentObjects] = spawnedObject;
                spawnerData.spawnableObjects[i].currentObjects += 1;                        
                Debug.Log(objectsSpawned.Length);
            }
        }
    }
}

spawnerData来自另一个类:

[CreateAssetMenu]
public class SurfaceSpawnerData : ScriptableObject
{
    public SpawnableObjects[] spawnableObjects;

    [System.Serializable]
    public class SpawnableObjects
    {
        public GameObject spawnablePrefab;
        public float spawnerStartHeight = 2f;
        public float spawnerEndHeight;
        public int currentObjects;
        public int numberOfObjects;
    }
}

如果我删除该行,当前一切正常:

objectsSpawned[spawnerData.spawnableObjects[i].currentObjects] = spawnedObject;

但是,在代码的那一行中,它只会生成无数个不会添加到数组中的对象。

感谢您的帮助。

0 个答案:

没有答案