如何修改统一c#上的代码,使其每30秒生成一次敌人,只有在战场上的敌人少于10个时。
目前,我在枚举器中有一个while循环,它将敌人生成为10,但在开始时才被调用,当敌人数量达到1时,我需要该函数来生成敌人。
谢谢。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateEnemies : MonoBehaviour
{
public GameObject theEnemy;
public int xPos;
public int zPos;
public int enemyCount;
void Start()
{
StartCoroutine(SpawnEnemy());
}
IEnumerator SpawnEnemy()
{
while (enemyCount < 10)
{
xPos = Random.Range(153, 203);
zPos = Random.Range(-76, 76);
Instantiate(theEnemy, new Vector3(xPos, 9, zPos), Quaternion.identity);
yield return new WaitForSeconds(0.9f);
enemyCount += 1;
}
}
}
发布于 2022-01-19 01:28:09
我根本没有测试过这段代码
嗨,Obito,让我向您展示这段代码,看看您是否可以实现它:
[Header("Spawning Properties")]
public GameObject enemyPrefab;
public Vector3 spawnPoint;
public int maxEnemies = 10;
public int minEnemies = 1;
//This is the time between each spawn.
public float spawnDelay = 0.9f;
public spawnTimer = 30f;
//Every enemy *needs* an 'Enemy' script, or tag, to identify what is an enemy.
public int EnemyCount => GameObject.FindObjectsOfType<Enemy>();
private void Awake()
{
spawnTimer = 30f;
}
private void Update()
{
spawnTimer -= Time.deltaTime;
//"Do I need to start spawning enemies?"
if(EnemyCount <= minEnemies && spawnTimer <= 0) {
StartCoroutine(SpawnEnemies());
}
}
private IEnumerator SpawnEnemies()
{
while(EnemyCount <= maxEnemies)
{
Instantiate(enemyPrefab, spawnPoint, Quaternion.identity);
yield return new WaitForSeconds(spawnDelay);
Debug.Log("Enemy " + EnemyCount + "/" + maxEnemies + " spawned.");
}
spawnTimer = 30f;
}
提示:如果你想建立一个“每波敌人”系统,你应该尝试这样做:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Spawning Properties")]
public GameObject enemyPrefab;
public Vector3 spawnPoint;
public int[] wavesCount = { 10, 14, 23, 40 };
public int minEnemiesPerWave = 1;
public int currentWave = 0;
//This is the time between each spawn.
public float spawnDelay = 0.9f;
private float spawnTimer = 30f;
//Every enemy *needs* an 'Enemy' script, or tag, to identify what is an enemy.
public int EnemyCount => GameObject.FindObjectsOfType<Enemy>();
private void Start() {
spawnTimer = 30f;
}
private void Update()
{
spawnTimer -= Time.deltaTime;
//"Do I need to start spawning enemies?"
if(EnemyCount <= minEnemiesPerWave && spawnTimer <= 0) {
StartCoroutine(SpawnEnemies());
}
}
private IEnumerator SpawnEnemies()
{
while(EnemyCount <= wavesCount[currentWave])
{
Instantiate(enemyPrefab, spawnPoint, Quaternion.identity);
yield return new WaitForSeconds(spawnDelay);
Debug.Log("Enemy " + EnemyCount + "/" + maxEnemies + " spawned.");
}
spawnTimer = 30f;
currentWave++;
}
}
https://stackoverflow.com/questions/70763936
复制相似问题