首页 > 解决方案 > 如何使用 SpawnCount 生成选定对象

问题描述

获取对象 && 获取其计数 SpawnCount

生成所有 20 个选定对象

看图片 遵循代码不只是示例。

using UnityEngine;

[System.Serializable]
public class ObjectToSpawn
{
    public GameObject Object;
    public int spawnCount;

}
public class LevelSpawner : MonoBehaviour
{
 public ObjectToSpawn[] itemToSpawn; // Select Obstacles To spawn
    public int maxSpawnObject;  // Total Object or Sum of All Spawn Count.
}

标签: c#unity3d

解决方案


所以在澄清评论中的事情之后,我会说你只是想做

public class LevelSpawner : MonoBehaviour
{
    public ObjectToSpawn[] itemToSpawn; 
    public int maxSpawnObject;

    // Wherever this is called e.g. in "Awake"
    public void Spawn()
    {
        // Keep track how many things you spawned in total
        var counter = 0;

        // iterate given items in order
        foreach(var item in itemToSpawn)
        {
            // Iterate spawnCount times for the current item
            for(var i = 0; i < item.spawnCount; i++)
            {
                // spawn the item
                Instantiate(item.Object);

                // increase the counter
                counter++;

                // return if max count is exceeded
                if(counter >= maxSpawnObject) return;
            }
        }
    }
}

推荐阅读