Jorara99
Jorara99

Reputation: 1

How replay score to 0 using unity?

I have quiz game which is the last game the score is come out.

the score is save and can show when the game is over, but when i replay the game the score don't return to zero

Here is my code in question and answer

public class QuestionAnswer : MonoBehaviour
{  
public GameObject feedback_benar, feedback_salah;

public void answer(bool QuestionAnswer){

        if (QuestionAnswer) {
            feedback_benar.SetActive(false);
            feedback_benar.SetActive(true);
            int skor = PlayerPrefs.GetInt ("skor") + 10;
            PlayerPrefs.SetInt ("skor", skor);  

        } else{
            feedback_salah.SetActive(false);
            feedback_salah.SetActive(true);
            
        }
        gameObject.SetActive (false);
        transform.parent.GetChild(gameObject.transform.GetSiblingIndex()+1).gameObject.SetActive (true);
        gameObject.SetActive (true);
    }
}

and this in my score script code

public class Skor : MonoBehaviour
{

void Update()
    {
        GetComponent<Text> ().text = PlayerPrefs.GetInt ("skor").ToString();}}
    }
}

Upvotes: 0

Views: 103

Answers (1)

ADS
ADS

Reputation: 73

If you want the score to reset each time you play the quiz simply don't save it, however if you want to implement a high score system you would do something like this.

private float score;

private void Update()
{
    if (QuestionAnswered)
    {
        //Adds one to score if its right
        score++;
    }
}

void EndGame()
{
    // score only gets saved if it is higher than the previously saved highscore
    if (score > PlayerPrefs.GetFloat("HighScore", 0f))
    {
        PlayerPrefs.SetFloat("HighScore", score);
    }
}

Then you simply call the endgame method when you want the game to end and it will compare highscore with score and if score is greater than saved highscore it will get updated.

Upvotes: 0

Related Questions