ScoreManager.cs
I've created a complete score management system for Unity! Here's what's included:
ScoreManager.cs - The main system featuring:
- Current score tracking
- Automatic high score saving (uses PlayerPrefs)
- Previous score storage
- Singleton pattern for easy access
- Event system for UI updates
ScoreUI.cs - UI display script that:
- Automatically updates when scores change
- Works with both TextMeshPro and legacy Unity Text
- Customizable text prefixes
GameExample.cs - Example implementation showing how to use the system in your game
using UnityEngine;
using System;
public class ScoreManager : MonoBehaviour
{
// Singleton instance
public static ScoreManager Instance { get; private set; }
// Current game session scores
private int currentScore = 0;
private int previousScore = 0;
// High score (persisted)
private int highScore = 0;
// Events for UI updates
public event Action OnScoreChanged;
public event Action OnHighScoreChanged;
// PlayerPrefs keys
private const string HIGH_SCORE_KEY = "HighScore";
private void Awake()
{
// Singleton pattern
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
LoadHighScore();
}
else
{
Destroy(gameObject);
}
}
///
/// Add points to the current score
///
public void AddScore(int points)
{
currentScore += points;
OnScoreChanged?.Invoke(currentScore);
CheckHighScore();
}
///
/// Set the score to a specific value
///
public void SetScore(int score)
{
currentScore = score;
OnScoreChanged?.Invoke(currentScore);
CheckHighScore();
}
///
/// Reset the current score (call this at the start of a new game)
///
public void ResetScore()
{
previousScore = currentScore;
currentScore = 0;
OnScoreChanged?.Invoke(currentScore);
}
///
/// Check if current score is a new high score and update if needed
///
private void CheckHighScore()
{
if (currentScore > highScore)
{
highScore = currentScore;
SaveHighScore();
OnHighScoreChanged?.Invoke(highScore);
}
}
///
/// Save high score to PlayerPrefs
///
private void SaveHighScore()
{
PlayerPrefs.SetInt(HIGH_SCORE_KEY, highScore);
PlayerPrefs.Save();
}
///
/// Load high score from PlayerPrefs
///
private void LoadHighScore()
{
highScore = PlayerPrefs.GetInt(HIGH_SCORE_KEY, 0);
}
///
/// Manually reset the high score (useful for testing or reset button)
///
public void ResetHighScore()
{
highScore = 0;
SaveHighScore();
OnHighScoreChanged?.Invoke(highScore);
}
// Getters
public int GetCurrentScore() => currentScore;
public int GetHighScore() => highScore;
public int GetPreviousScore() => previousScore;
///
/// Check if the current score is a new high score
///
public bool IsNewHighScore()
{
return currentScore >= highScore && currentScore > 0;
}
}
Comments