Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Stop counter when game over and store the value

Discussion in 'Scripting' started by merde10, Feb 18, 2016.

  1. merde10

    merde10

    Joined:
    Dec 29, 2015
    Posts:
    6
    Hello guys,

    For my new game in unity, i create a java script that allows to count when the player is playing and display the value in a GUIText.

    But i have some issues.

    In the game, the count start and the GUIText shows the value of the count.
    But when i come to the game over, the count doesn't stop.

    In the quit scene, the GUIText that shows the value of the count of the game scene, restart from 0 and it don't stop.

    here is the script:

    var Counter : int = 0;
    var score : GUIText;

    function Start () {

    }

    function Update () {

    Counter++;
    score.text = Counter.ToString();

    }

    So what i want to do is to stop the count when the game over comes, and store the value so in the next scene, the GUIText shows the final value.

    How can i do that?

    Thanks a lot :)

    Regards, Ophélia.
     
  2. Limeoats

    Limeoats

    Joined:
    Aug 6, 2014
    Posts:
    104
    My guess is that this script continues to run even once the game over happens. Since you are incrementing Counter in the Update function, and this script continues running, you will continue to see a higher score.

    You can solve this in a few ways. My suggestion is to have some kind of GameManager class that you can access from this script. In your Update function, you can say something like..

    Code (JavaScript):
    1. function Update() {
    2.     if (GameManager.isPlaying()) {
    3.         Counter++;
    4.     }
    5.     else {
    6.         Counter = 0;
    7.     }
    8.     score.text = Counter.ToString();
    9. }
    Then, all you'd need to do is change a flag in your game manager whenever the game goes from playing -> not playing or vice-versa.
     
  3. merde10

    merde10

    Joined:
    Dec 29, 2015
    Posts:
    6
    thank you for you reply,

    i don't master how to create a game manager yet.

    So i think it's easier for me to do it in one single script.

    I just find that i can store the value of my count with PlayerPref, but how can i call it?