Why is my Unity Game crashing whenever Time Left is close to 0?
So, currently, in my game, I'm trying to make a Game Manager that does all of the background management and running. Currently, all it does it make sure that some variables are met, and then spawn in a new character and run their AI so that they can fulfill the rest of their tasks. The code looks like this:
public GameObject Person;
public Transform Spawn1;
public Transform Spawn2;
public int PlayersInStore;
public float TimeLeft = 5;
public bool Ready = false;
// Start is called before the first frame update
void Start()
{
TimeLeft = Random.Range(5.0f, 15.0f);
}
// Update is called once per frame
void Update()
{
if(TimeLeft > 0.0f)
{
TimeLeft -= Time.deltaTime;
}
if (TimeLeft <= 0.0f)
{
Ready = true;
}
if (PlayersInStore < 5 && Ready == true)
{
SendInPlayer();
Ready = false;
}
}
public void SendInPlayer()
{
PlayersInStore = PlayersInStore + 1;
int WhichSpawn = Random.Range(1, 3);
Transform SpawnPoint = Spawn1;
Transform FaceTowards = Spawn2;
if(WhichSpawn == 1)
{
SpawnPoint = Spawn1;
FaceTowards = Spawn2;
}
if (WhichSpawn != 1)
{
SpawnPoint = Spawn2;
FaceTowards = Spawn1;
}
GameObject Player = Instantiate(Person, new Vector2 (SpawnPoint.position.x, SpawnPoint.position.y), Quaternion.identity);
Player.SetActive(true);
TimeLeft = Random.Range(5.0f, 15.0f);
Player.GetComponent<PlayerAI>().SpawnedIn();
}
The problem is that every time I run my code, whenever Time Left becomes really low (around 0.02f) it will crash Unity, nothing in the engine will be interactable and I can't stop running the game. The only way to fix it is to go into Task Manager and Force Shutdown Unity, then restart it. I don't know what the problem is, I think it may have to do with the if statements in the Update() function, but I have no clue and I don't want to have to keep restarting and crashing Unity when I could just come here and see if anyone knows how to fix it.
Even without the first if statement that checks if TimeLeft > 0, the timer still stops just above 0. So the Update() function must have stopped being called with the crash, still not sure what is causing it though.