C# script to make simple score system with load and save options.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // ? 2017 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class SimpleScore : MonoBehaviour { [SerializeField] private float minScore = 0.0f; [SerializeField] private float score = 0.0f; [SerializeField] private bool loadScore = false; [SerializeField] private bool saveScore = false; [SerializeField] private bool resetSavedScore = false; [SerializeField] private string playerPrefsName = "Score"; [SerializeField] string initialScoreText; [SerializeField] bool useTextText = false; [SerializeField] Text scoreText; // Use this for initialization void Start () { GetScoreText(); if (loadScore) { SaveIfNotExisting(); LoadScore(); } if (resetSavedScore) { Reset(); } UpdateText(); } void UpdateText() { scoreText.text = initialScoreText + score.ToString("N0"); } void SaveIfNotExisting() { if (!PlayerPrefs.HasKey(playerPrefsName)) { PlayerPrefs.SetFloat(playerPrefsName, score); } } void LoadScore() { score = PlayerPrefs.GetFloat(playerPrefsName); } void SaveScore() { if (saveScore) { PlayerPrefs.SetFloat(playerPrefsName, score); } } void GetScoreText() { if (useTextText) { initialScoreText = scoreText.text; } } //Call that function where you want to increase your score public void AddScore(float value) { score += value; UpdateText(); SaveScore(); } //Call that function where you want to decrease your score public void LoseScore(float value) { score -= value; UpdateText(); SaveScore(); } public void Reset() { score = minScore; UpdateText(); SaveScore(); } }
Unity C# Simple Score System