- Home /
End game after livesLeft = 0
Hi
I have a game that is currently working with a countdown timer using Time.deltaTime. But I need to use a life counter as opposed to a time counter.
I have a destroyer script which is based outside of the visible screen to that GameObjects are destroyed if they manage to get past the player, and if they do the player loses a life, but I cannot get the game to end when livesLeft = 0.
Currently the timer version has the countdown timer on the GameController script: void Start () {
if (cam == null) {
cam = Camera.main;
}
Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
Vector3 targetWidth = cam.ScreenToWorldPoint (upperCorner);
float flapWidth = flap.renderer.bounds.extents.x;
maxWidth = targetWidth.x - flapWidth;
StartCoroutine (Spawn());
timerText.text = "LIVES: " + Mathf.RoundToInt (timeLeft);
timerText.text = "Time Left:\n" + Mathf.RoundToInt (timeLeft);
}
void FixedUpdate () {
timeLeft -= Time.deltaTime;
if (timeLeft < 0) {
timeLeft = 0;
}
timerText.text = "Time Left:\n" + Mathf.RoundToInt (timeLeft);
}
IEnumerator Spawn () {
yield return new WaitForSeconds (2.0f);
while (timeLeft > 0) {
Vector3 spawnPosition = new Vector3 (Random.Range (-maxWidth, maxWidth), transform.position.y, 0.0f);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (flap, spawnPosition, spawnRotation);
yield return new WaitForSeconds (Random.Range(1.0f, 1.0f));
}
yield return new WaitForSeconds (1.0f);
gameOverText.SetActive (true);
yield return new WaitForSeconds (1.0f);
restartButton.SetActive (true);
}
And the destroyer also has the life lost script: void Start () { lifescore = 5; UpdateScore ();
}
void OnTriggerEnter2D () {
lifescore -= lifeValue;
UpdateScore ();
}
void UpdateScore () {
livesText.text = "LIVES: " + lifescore;
if (lifescore < 0) {
lifescore = 0;
gameController.CancelInvoke("Spawn");
}
livesText.text = "LIVES: " + lifescore;
}
If I put them both together the timer counts down as expected and also the players lives are reduced every time they miss a target, but I need the game to end after all the lives are lost so that I can remove the timer section, as this is not a timed game.
Any help would be appreciated. Thanks.
Your answer
Follow this Question
Related Questions
2d rotation and translation issue 1 Answer
Can i change a ball with Rigidbody2D with CircleCollider2D to liquid on collision 0 Answers
Move Object by dragging (mobile) makes the balls fall from the cup 1 Answer
why when i try to add my script to the "player" it says can not can not add script 1 Answer