Just some pre-info, some code was made by AI, so I understand the reluctance to help. Don't treat it as me wanting to debug it, though, since it was for a game jam that has just concluded and I want to learn what to do in the future.
In our game, player could possess any bot in the game. To do that, I made all bots use an interface with their own move, fire, etc. methods. Then the player controller would have an instance of this interface declared, and its methods would fire the instance's methods. Pseudocode time:
void Move();
}```
```public class Bot : MonoBehaviour, IControllable{
public void Move(){
Debug.Log(name+" moves");
}
}```
```public class PlayerController : MonoBehaviour{
public IControllable currentControllable;
public OnKeyPress(){
currentControllable.Move();
}
}```
Then another system would choose the controllables for the player by just doing GetComponent<IControllable>(). If the Bot was to die, then a script would find another living one and become the player's currentControllable. The problem is that while playtesting we found a lot of null errors, mostly MissedReferenceException and NullReferenceException. Common situations were:
- Deleting multiple bots (i.e. in-game bomb calling Destroy() in a foreach loop for each bot)
- Two only bots on the map dying at the same time (even if we made sure that before the last one is deleted, a new one would be instantiated to prevent there being an empty map)
We managed to just obscure the errors because they tended to happen after player finishes a game, however no matter how many `PlayerController.currentControllable != null` I put, the code would still try to access it and throw the damned null errors. The PlayerController script was never in any of the spawned Bots, so it's not like it was being destroyed.
I just want to know if there is a better way to safeguard against these errors. We're talking about a system where bots with this system are instantiated dynamically, with a system listing them by updating its list through a FindObjectsByType().
Sorry if I don't happen to make much sense :c