新建一个tag “ZombieSpawn”,将物体ZombieSpawn添加这个tag,然后多复制几个放在不同的位置上
打开之前的脚本GameManaer_ZombieSpawner
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class GameManaer_ZombieSpawner : NetworkBehaviour {
//僵尸的预制件
[SerializeField]
GameObject zombiePrefab;
//僵尸重生点
private GameObject[] zombieSpawns;
//计数器
private int counter;
//僵尸的数量
private int numberOfZombies = 50;
//僵尸的最大数量
private int maxNumberOfZombies = 80;
//僵尸重生的时间
private float waveRate = 10;
//僵尸是否能够重生
private bool isSpawnActivated = true;
public override void OnStartServer()
{
//寻找标签为ZombieSpawn的物体,即僵尸的重生点
zombieSpawns = GameObject.FindGameObjectsWithTag("ZombieSpawn");
//开启协程
StartCoroutine(ZombieSpawner());
}
IEnumerator ZombieSpawner()
{
for (; ; )
{
//等待僵尸的重生时间
yield return new WaitForSeconds(waveRate);
//寻找标签为Zombie的物体,即僵尸
GameObject[] zombies = GameObject.FindGameObjectsWithTag("Zombie");
//如果僵尸的数量小于最大数量,调用函数CommenceSpawn
if (zombies.Length < maxNumberOfZombies)
{
CommenceSpawn();
}
}
}
void CommenceSpawn()
{
if (isSpawnActivated)
{
for (int i = 0; i < numberOfZombies; i++)
{
//从多个重生点中随机的选取其中的一个
int randomindex = Random.Range(0, zombieSpawns.Length);
//调用SpawnZombies函数,将随机出来的重生点的位置传递过去
SpawnZombies(zombieSpawns[randomindex].transform.position);
}
}
}
//在指定的位置(spawnPos)上生成僵尸
void SpawnZombies(Vector3 spawnPos)
{
counter++;
GameObject go = GameObject.Instantiate(zombiePrefab, spawnPos, Quaternion.identity) as GameObject;
NetworkServer.Spawn(go);
go.GetComponent<Zombie_ID>().zombieID = "Zombie " + counter;
}
}