Reputation: 333
So I am making a rocket app, still early into development. I wrote code that counts a score when I collide with objects. How to make it so it saves my highest score and can display it? As soon as I leave my scene it sets the score back to 0 :( please help thank you!
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class POINTS1 : MonoBehaviour
{
public Text countText;
public Text winText;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
count = count + 100;
SetCountText();
}
if (other.gameObject.CompareTag("minus300"))
{
other.gameObject.SetActive(false);
count = count -300;
SetCountText();
}
}
void SetCountText()
{
countText.text = "Score: " + count.ToString();
if (count >= 5000)
{
winText.text = "Good Job!";
}
}
}
EDIT: So I tried the code you kindly provided, am I doing something wrong? It doesn't work... I think we might need a GUI element to display the highest score.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class POINTS1 : MonoBehaviour
{
public Text countText;
public Text winText;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
count = count + 100;
SetCountText();
}
if (other.gameObject.CompareTag("minus300"))
{
other.gameObject.SetActive(false);
count = count -300;
SetCountText();
}
}
void SetCountText()
{
PlayerPrefs.SetInt("score", count);
PlayerPrefs.Save();
count = PlayerPrefs.GetInt("score", 0);
countText.text = "Score: " + count.ToString();
if (count >= 5000)
{
winText.text = "Good Job!";
}
}
}
//PlayerPrefs.SetInt("score", count);
//PlayerPrefs.Save();
//count = PlayerPrefs.GetInt("score", 0);
Upvotes: 2
Views: 142
Reputation: 2516
What you want is the PlayerPrefs class. PlayerPrefs allows you to store data between sessions of your game.
You can save data by calling PlayerPrefs.Set for any supported data type (int, float or string), and get it by using the corresponding PlayerPrefs.Get.
For example, if you want to save the score, you can do it like so.
PlayerPrefs.SetInt("score", count);
PlayerPrefs.Save();
And get it back by
count = PlayerPrefs.GetInt("score", 0);
Upvotes: 2