Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

how to add a total score to playerprefs

Discussion in 'Getting Started' started by CyberInteractiveLLC, Sep 23, 2017.

  1. CyberInteractiveLLC

    CyberInteractiveLLC

    Joined:
    May 23, 2017
    Posts:
    306
    Hi, i'm trying to add total lifetime score the player has achieved to playerprefs, at the moment i have this script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine.SceneManagement;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class Game_Controller : MonoBehaviour
    8. {
    9.     private int score;
    10.  
    11.     public GUIText scoreText;
    12.     public GUIText lifetimescoreText;
    13.  
    14.     void Start ()
    15.     {
    16.         Gameoverpanel.SetActive (false);
    17.        lifetimescoretext.text = "Life time Score: " + PlayerPrefs.GetInt ("LifeTimeScore", 0).ToString ();
    18.         highscoreText.text = "";
    19.         Time.timeScale = 1f;
    20.         score = 0;
    21.         UpdateScore ();
    22.     }
    23.  
    24.     void Update ()
    25.     {
    26.             inGamehighscoreText.text = "Life time Score: " + PlayerPrefs.GetInt ("LifeTimeScore" + score).ToString();
    27.         }
    28.  
    29.  
    30.  
    31.  
    32.     public void AddScore (int newScoreValue)
    33.     {
    34.         score += newScoreValue;
    35.         UpdateScore ();
    36.     }
    37.  
    38.     void UpdateScore ()
    39.     {
    40.         scoreText.text = "Score: " + score;
    41.     }
    42.  
    43.  
    44. }

    i removed unrelated code, i have other script that adds score to the void AddScore function each time we kill an enemy, which works fine but the total life time score is where i have problems with
     
  2. jchester07

    jchester07

    Joined:
    Jun 28, 2016
    Posts:
    24
    Here's how I do it
    Code (CSharp):
    1. int currentLifetimeScore = PlayerPrefs.GetInt ("LifeTimeScore");
    2. int newLifeTimeScore = currentLifetimeScore + score;
    3. PlayerPrefs.SetInt ("LifeTimeScore", newLifeTimeScore);
    You can place it in your AddScore function.
    I also suggest to place your line of code in Update() function to UpdateScore() function so that it would only update when the score is updated to minimize calls on playerprefs.