//Removes dead players/npcs from data structure, its important that the NPCThread is done looping through the npcs, // because removing dead stuff will break a foreach loop void removeDeadStuff() { if (this._deadNpcs.Count > 0 || this._deadNpcs.Count > 0) { if (this._npcs.Count <= 1) { this._npcThreads.stopThreads(); this._deadNpcs.Clear(); this._deadPlayers.Clear(); this._ready = false; NPCWorldView.clear(); return; } var players = NPCWorldView.npcs; foreach (int dead in this._deadPlayers) { this._players.Remove(dead); players.Remove(dead); } var npcs = NPCWorldView.npcs; foreach (int dead in this._deadNpcs) { this._npcs.Remove(dead); npcs.Remove(dead); } this._deadNpcs.Clear(); this._deadPlayers.Clear(); } }
//Spawn NPCs, then register players/npcs in datastructures in this class, and NPCWorldView //Populates the 4 key datastructures for this class and the NPCThread. //This class uses a list of players and a list of NPCs. //These lists are used to update a list of players and NPCs in NPCWorldView. //The need for keeping two list comes from the fact that the Unity API is not thread safe. //The NPCThread uses a thread safe representation of the World provided by NPCWorldView. private IEnumerator init() { while (!WorldData.ready) { yield return(0); } //Wait for all NPCs to spawn while (GameObject.FindGameObjectsWithTag("npc").Length != _npcCount) { yield return(0); } //Wait for all players to spawn, +1 for localplayer while (!GameInfo.playersReady) { yield return(0); } NPCWorldView.init(); //gather data about players for the NPCs GameObject localPlayer = GameObject.FindGameObjectWithTag("Player"); GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); //Add players to the list of players this._players.Add(0, localPlayer); for (int i = 0; i < enemies.Length; i++) { this._players.Add(i + 1, enemies[i]); } //Add players to NPCWorldView so that the NPCThread can use data about them var players = NPCWorldView.players; for (int i = 0; i < this._players.Count; i++) { players.Add(i, new NPCWorldView.GameCharacter(i)); } GameObject[] npcs = GameObject.FindGameObjectsWithTag("npc"); for (int i = 0; i < npcs.Length; i++) { this._npcs.Add(i, npcs[i]); NPCWorldView.npcs.Add(i, new NPCWorldView.GameCharacter(i)); } NPCWorldView.ready = true; this._npcThreads = new NPCThreadManager(_npcThreadCount); this._ready = true; //StartCoroutine(debug()); }
void OnDestroy() { this._npcThreads.stopThreads(); NPCWorldView.clear(); }
//It's important to stop the NPCThread when quitting void OnApplicationQuit() { this._npcThreads.stopThreads(); NPCWorldView.clear(); }