C# script to make simple score system with load and save options.

Content not available.
Please allow cookies by clicking Accept on the banner

 

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
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close