i am trying to stop spawning when the game is over
I don't know what is wrong with it any help would be great!! what is below is my code
public class GameManagerX : MonoBehaviour
{
public TextMeshProUGUI scoreText;
private int score;
public TextMeshProUGUI gameOverText;
public GameObject titleScreen;
public Button restartButton;
public List<GameObject> targetPrefabs;
private float spawnRate = 1.5f;
public bool isGameActive;
private float spaceBetweenSquares = 2.5f;
private float minValueX = -3.75f; // x value of the center of the left-most square
private float minValueY = -3.75f; // y value of the center of the bottom-most square
// start is called before the first frame update
void Start()
{
StartCoroutine(SpawnTarget());
score = 0;
UpdateScore(0);
}
// Start the game, remove title screen, reset score, and adjust spawnRate based on difficulty button clicked
public void StartGame()
{
spawnRate /= 5;
isGameActive = true;
StartCoroutine(SpawnTarget());
score = 0;
scoreText.text = "Score: " + score;
UpdateScore(0);
titleScreen.SetActive(false);
}
// While game is active spawn a random target
IEnumerator SpawnTarget()
{
while (isGameActive)
{
yield return new WaitForSeconds(spawnRate);
int index = Random.Range(0, targetPrefabs.Count);
if (isGameActive)
{
Instantiate(targetPrefabs[index], RandomSpawnPosition(), targetPrefabs[index].transform.rotation);
}
}
}
// Generate a random spawn position based on a random index from 0 to 3
Vector3 RandomSpawnPosition()
{
float spawnPosX = minValueX + (RandomSquareIndex() * spaceBetweenSquares);
float spawnPosY = minValueY + (RandomSquareIndex() * spaceBetweenSquares);
Vector3 spawnPosition = new Vector3(spawnPosX, spawnPosY, 0);
return spawnPosition;
}
// Generates random square index from 0 to 3, which determines which square the target will appear in
int RandomSquareIndex()
{
return Random.Range(0, 4);
}
// Update score with value from target clicked
public void UpdateScore(int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = "Score: " + score;
}
// Stop game, bring up game over text and restart button
public void GameOver()
{
gameOverText.gameObject.SetActive(true);
restartButton.gameObject.SetActive(true);
isGameActive = false;
}
// Restart game by reloading the scene
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
private float timer = 60;
public TextMeshProUGUI textTimer;
private void Update()
{
if (isGameActive)
{
CountdownTimer();
}
if (timer < 0)
{
GameOver();
}
}
public void CountdownTimer()
{
timer -= Time.deltaTime;
textTimer.SetText("Time: " + Mathf.Round(timer));
}
Comment
Have you tried simply calling StopCorountine("SpawnTarget")
$$anonymous$$ake isGameActive public and check if it is false after the game ends using the inspector.