Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Omega2077 · Jul 09, 2015 at 03:18 PM · scripting problemscriptingbasicsscorescore systemscoring

I want my score to reset back to 0 but keep my highscore saved

I am using unity 5.0.2 and have a Text component to display my score and highscore on screen not a GUI. I have tried many different methods to get the GUI to work but all failed. My score works just fine when you collect coins it adds a point but the problem is when my timer hits 0 and restarts the game again I want to save and show my highscore and reset my score back to 0. I am in desperate need of help to fix this as it is for my app that is due to be released within the next two days. Please help?

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class ScoreManager : MonoBehaviour {
     
     public static int score;
     public static int highscore;
     
     Text text;
     
     void Start()
     {
         text = GetComponent<Text> ();
         
         score = 0;
         
         highscore = PlayerPrefs.GetInt("highscore", highscore);
         
     }
     
     void Update()
     {
         if (score > highscore)
             highscore = score;
         text.text = "" + score; }
     
     
     void ResetTime() {
         
         PlayerPrefs.SetInt("highscore", highscore);
     }
     
     public static void AddPoints (int pointsToAdd)
     {
         score += pointsToAdd;
     }
     
     public static void Reset()
     {
         score = 0;
     }
 }

 
Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Pflobus · Jul 09, 2015 at 03:19 PM 0
Share

Just a question, are you following the Unity tutorial on the endless runner?

avatar image ilovemypixels · Jul 09, 2015 at 03:26 PM 1
Share

You need to use the local data available to you that will save a file on the device. Here is what I have in my app.

 public void Save() {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
 
         PlayerData data = new PlayerData();
 
         data.timePlayed = timePlayed;
         data.totalTaps = totalTaps;
         data.timesOpened = timesOpened;
 
         bf.Serialize(file, data);
         file.Close();
     }
 
     public void Load() {
         if(File.Exists(Application.persistentDataPath + "/playerInfo.dat")) {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", File$$anonymous$$ode.Open);
             PlayerData data = (PlayerData)bf.Deserialize(file);
             file.Close();
 
             timePlayed = data.timePlayed;
             totalTaps = data.totalTaps;
             timesOpened = data.timesOpened;
         }
     }

Hopefully this might get you started, it works to a point with $$anonymous$$e currently, although if you completely close the app on your phone, double tap home and swipe it away, it seems to loose the data.

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading

Here is the tutorial I followed.

avatar image Hexer · Jul 09, 2015 at 08:24 PM 1
Share
 void Update()
      {
          if (score > highscore)
              highscore = score;
          text.text = "" + score; }
      
      
      void ResetTime() {
          
          PlayerPrefs.SetInt("highscore", highscore);
      }

When does ResetTime() gets called?

Just put the PlayerPrefs.SetInt("highscore", highscore); in the void Update() in the if statement, when score>highscore

you also have to invoke the void Reset() before it gets called.

avatar image NinjaISV · Jul 09, 2015 at 08:31 PM 0
Share

Good point. Clearly it isn't public, so it can't be called from outside the class, and yet, it's not called anywhere in the class. Thus, it must never be saving the highscore, so when it loads it, there's nothing to load.

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by NinjaISV · Jul 09, 2015 at 07:05 PM

EDIT: Thanks to Hexer for pointing this out. You're never calling ResetTime() thus resulting in the highscore never getting saved. So when you go to load it on Start(), it's loading nothing because there's nothing there to load. You'll have to call ResetTime() at the end of the game to save the highscore.

This code is pretty self explanatory. You can save and load to the computer without the use of the insecure prefab saving system.

 using System.Runtime.Serialization.Formatters.Binary;
 using System.Collections;
 using UnityEngine.UI;
 using UnityEngine;
 using System.IO;
 using System;
 
 public class ScoreManager : MonoBehaviour
 {
     public int score;
     public int highscore;
 
     Text scoreText;
 
     void Start ()
     {
         scoreText = GetComponent<Text>();
         score = 0;
 
         Load();
     }
 
     void Update ()
     {
         if(score > highscore)
         {
             highscore = score;
             scoreText.text = highscore.ToString();;
         }
     }
 
     public void AddScore (int addedScorePoints)
     {
         score += addedScorePoints;
     }
 
     public void ResetScore ()
     {
         score = 0;
     }
 
     public void Save ()
     {
         if(Directory.Exists(Application.dataPath + "/Save data/") == false)
             Directory.CreateDirectory(Application.dataPath + "/Save data/");
         BinaryFormatter bf = new BinaryFormatter ();
         FileStream file = File.Create (Application.dataPath + "/Save data/Score.secure");
         ScoreData data = new ScoreData ();
         
         data.highscore = this.highscore;
         
         bf.Serialize (file, data);
         file.Close ();
     }
 
     public void Load ()
     {
         if(File.Exists(Application.dataPath + "/Save data/Score.secure"))
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.dataPath + "/Save data/Score.secure", FileMode.Open);
             ScoreData data = (ScoreData)bf.Deserialize(file);
             file.Close();
             
             this.highscore = data.highscore;
             scoreText.text = highscore.ToString();
         }
     }
 }
 
 [Serializable]
 class ScoreData
 {
     public int highscore;
 }


All we do in this code is save out highscore to a file, then load it again when needed.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Diet-Chugg · Jul 09, 2015 at 05:06 PM

I would make your Manager a singleton and make it persist between scenes.

Like this:

 public class ScoreManager : MonoBehaviour
 {
     public static ScoreManager instance;
     public int score;
     public int highscore;
 
     public void OnEnable()
     {
         if (instance == null)
         {
             DontDestroyOnLoad(this.gameObject);//Make this Scoremanager object stay in all scenes
             instance = this;//Make this ScoreManager accessible anywhere with ScoreManager.instance.score for example
             highscore = PlayerPrefs.GetInt("HighScore",0);//0 if there isn't already a playerPref called "HighScore"
         }
         else
         {
             Destroy(this);//When you load a scene if you already have a ScoreManager that persists between scenes. Don't allow more than one to be created
         }
     }
 
     public void Reset()
     {
         score = 0;
     }
 
     public void SaveScore()
     {
         PlayerPrefs.SetInt("HighScore",highscore);
     }
 
     public void AddPoints(int points)
     {
         score += points;
         if (score > highscore)
             highscore = score;
     }
 
 
 }

From there have your UI access the ScoreManager with ScoreManager.instance.score in a script on the UI that's seperate from the ScoreManager

Call SaveScore when the game finishes and addPoints whenever the player gets points.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by anurag7991 · Jul 28, 2018 at 11:35 AM

using UnityEngine; using System.Collections; using UnityEngine.UI;

public class ScoreManager : MonoBehaviour {

  public static int score;
  public static int highscore;
  
  Text text;
  
  void Start()
  {
      text = GetComponent<Text> ();
      
      score = 0;
      
      highscore = PlayerPrefs.GetInt("highscore", highscore);
      
  }
  
  void Update()
  {
      if (score > highscore)
          highscore = score;
      text.text = "" + score; }
  
  
  void ResetTime() {
      
      PlayerPrefs.SetInt("highscore", highscore);
  }
  
  public static void AddPoints (int pointsToAdd)
  {
      score += pointsToAdd;
  }
  
  public static void Reset()
  {
      playerprefs.DeleteKey("score");
  }

}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Scoring System 3 Answers

How to increase score by one per second when you are holding an object 2 Answers

How to create a score manager script involving awarding points from multiple objects? 2 Answers

Scoring help ! 1 Answer

How to save score for survival time? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges