统一/如何设置敌人生成的限制?

Unity / How to set Limit for enemy spawn?

我成功生成了敌人,但它们一直在生成。怎么设置限制才能避免不断刷怪?

我已尝试添加 spawnLimit 和 spawnCounter 但无法使其正常工作。

var playerHealth = 100;     // Reference to the player's heatlh.
var enemy : GameObject;                // The enemy prefab to be spawned.
var spawnTime : float = 3f;            // How long between each spawn.
var spawnPoints : Transform[];         // An array of the spawn points this enemy can spawn from.


function Start ()
{
    // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
    InvokeRepeating ("Spawn", spawnTime, spawnTime);
}


function Spawn ()
{
    // If the player has no health left...
    if(playerHealth <= 0f)
    {
        // ... exit the function.
        return;
    }


    // Find a random index between zero and one less than the number of spawn points.
    var spawnPointIndex : int = Random.Range (0, spawnPoints.Length);

    // Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

你可以使用这种计数器:

int maxEnemies = 100;
int enemiyCounter = 0;

并在 Spawn() 中添加:

if(enemiyCounter < maxEnemies){
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
    enemyCounter++;
}

而不是

Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

@ukasz-motyczka 给出的答案非常适合一次性生成,但如果你想要连续生成(每次杀死敌人时它都会被替换),那么你需要动态计算有多少有敌人。

Duck 在 how to count enemies

上给出了很好的答案

如果您将他的代码与 ukasz-motyczka 的代码结合起来,那么您可以删除该变量以跟踪您产生了多少敌人,因为您正在动态计算它们。你会得到这样的东西:

int maxEnemies = 100;

并在 Spawn()

// to count the number of objects:
var enemyCount : int = GameObject.FindGameObjectsWithTag("Enemy").Length;

if(enemyCount < maxEnemies){
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

当您想停止生成敌人时使用 CancelInvoke("spawn");

如果您正在玩 invoke()InvokeRepeating()

,您应该了解 CancelInvoke()