Unity /如何设置敌人产卵的限制?

时间:2016-12-28 18:59:50

标签: javascript unity3d unity5 unityscript

我设法产生敌人,但他们继续产卵。如何设置限制以避免不断产生?

我尝试添加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);
}

3 个答案:

答案 0 :(得分:2)

您可以使用这种计数器:

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);

答案 1 :(得分:1)

@ 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);

答案 2 :(得分:1)

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

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

,您应该知道InvokeRepeating()