Ova

How do you make a scoreboard in unity?

Published in Unity Game Development 6 mins read

Creating a scoreboard in Unity involves setting up UI elements, writing C# scripts to manage the score value, and linking score updates to in-game events. It's a fundamental feature for most games, providing players with immediate feedback on their performance.

How to Make a Scoreboard in Unity?

A scoreboard in Unity is typically comprised of a UI Text element that displays the player's current score, updated dynamically as gameplay progresses. Here's a step-by-step guide to implement one:

1. Setting Up the Score Display UI

The first step is to create the visual element that will show the score on screen.

  • Add UI Text:
    • In the Unity Editor, navigate to GameObject > UI > Text - TextMeshPro.
    • If prompted, import the TMP Essentials.
    • This action will also create a Canvas and an EventSystem if they don't already exist. The Canvas is where all UI elements reside.
  • Position and Resize:
    • Select the newly created Text (TMP) object in the Hierarchy.
    • In the Inspector, adjust its Rect Transform properties. Common positions for a scoreboard are the top-left or top-right corners of the screen.
    • Use the Anchor Presets (the square button with arrows) to quickly snap it to a corner, like Top-Left.
    • Adjust Pos X, Pos Y, Width, and Height to ensure it's visible and doesn't overlap other UI elements.
  • Edit Text Properties:
    • With the Text (TMP) object selected, locate the TextMeshPro - Text component in the Inspector.
    • Change the Text Input field to an initial value, such as "Score: 0".
    • Font Asset: Choose a suitable font.
    • Font Size: Increase the Font Size for readability.
    • Color: Adjust the Color to match your game's aesthetic.
    • Alignment: Set the Alignment (e.g., Left or Center) to control how the text is justified within its Rect Transform.

2. Initializing Score Variables and Text

Next, you'll create a C# script to manage the score data and link it to your UI Text element.

  • Create a Score Manager Script:

    • In your Project window, right-click in a suitable folder (e.g., Scripts) > Create > C# Script. Name it ScoreManager.
    • Create an empty GameObject in your scene (e.g., GameObject > Create Empty), name it ScoreManager, and attach your ScoreManager.cs script to it.
  • Declare Variables:

    • Open ScoreManager.cs in your code editor.
    • You'll need a variable to store the current score and a reference to the TextMeshProUGUI component to update the displayed text.
    using UnityEngine;
    using TMPro; // Important for TextMeshPro
    
    public class ScoreManager : MonoBehaviour
    {
        public static ScoreManager instance; // Singleton pattern for easy access
    
        public TextMeshProUGUI scoreText; // Reference to the UI Text component
        public int currentScore = 0;      // The actual score value
    
        void Awake()
        {
            if (instance == null)
            {
                instance = this;
            }
            else
            {
                Destroy(gameObject); // Ensures only one instance exists
            }
        }
    
        void Start()
        {
            // Initialize the displayed score
            UpdateScoreText();
        }
    
        // Method to update the UI text
        void UpdateScoreText()
        {
            if (scoreText != null)
            {
                scoreText.text = "Score: " + currentScore.ToString();
            }
        }
    }
  • Assign the UI Text:

    • Back in the Unity Editor, select the ScoreManager GameObject.
    • In its Inspector, drag your Text (TMP) object from the Hierarchy into the Score Text field of the ScoreManager script component.

3. Creating an Update Score Method

To dynamically change the score, you'll implement a method that can be called from other scripts.

  • Implement AddScore Method:

    • Add the following method to your ScoreManager.cs script:
    public void AddScore(int points)
    {
        currentScore += points; // Increment the score
        UpdateScoreText();      // Refresh the UI display
        Debug.Log("Score: " + currentScore); // For debugging purposes
    }
    • The UpdateScoreText() method should be placed within the ScoreManager script as shown in the previous step.

4. Triggering Score Updates from Game Events

Now, integrate the score update logic with your game's events, such as destroying targets or collecting items.

  • Example: Adding Score on Target Destruction:

    • Imagine you have a Target script attached to game objects that players can destroy.
    • In the Target script, you would define a point value for that target.
    using UnityEngine;
    
    public class Target : MonoBehaviour
    {
        public int pointValue = 10; // Points awarded for destroying this target
    
        void OnCollisionEnter(Collision collision)
        {
            // Example: If hit by a "Bullet"
            if (collision.gameObject.CompareTag("Bullet"))
            {
                // Add score using the ScoreManager instance
                if (ScoreManager.instance != null)
                {
                    ScoreManager.instance.AddScore(pointValue);
                }
    
                // Instantiate an explosion effect (see next step)
                // Assuming you have an explosion prefab
                // GameObject explosion = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
                // Destroy(explosion, 2f); // Destroy explosion after a duration
    
                Destroy(gameObject); // Destroy the target itself
                Destroy(collision.gameObject); // Destroy the bullet
            }
        }
    }
  • Assign Point Values:

    • Select your target prefabs or objects in the Unity Editor.
    • In the Inspector for the Target script, adjust the Point Value for each target type. This allows different targets to award different amounts of points.

5. Adding Visual and Audio Feedback (Optional but Recommended)

Enhancing the player experience with visual and audio cues when score events occur is crucial.

  • Particle Explosions/Effects:
    • When a target is destroyed, you can instantiate a particle system to create an explosion effect.
    • Create a new Particle System (e.g., GameObject > Effects > Particle System). Design your explosion effect.
    • Save it as a Prefab by dragging it from the Hierarchy into your Project window.
    • Add a public GameObject explosionPrefab variable to your Target script and assign your explosion prefab in the Inspector.
    • Uncomment the Instantiate(explosionPrefab, ...) and Destroy(explosion, ...) lines in the OnCollisionEnter method of your Target script.
  • Sound Effects:
    • Similarly, you can play a sound effect when points are awarded. This could be done through an AudioSource on the target itself, or by having a central AudioManager that plays sounds.

6. Extending to High Scores and Leaderboards

Once you have a basic score, you might want to track high scores or even create a full leaderboard.

  • Saving High Scores:
    • Use Unity's PlayerPrefs to save and load high scores locally.
    • In your ScoreManager or a separate GameManager script, after a game ends, compare currentScore with PlayerPrefs.GetInt("HighScore", 0). If currentScore is higher, save it: PlayerPrefs.SetInt("HighScore", currentScore);.
    • To display it, you'd load it: int highScore = PlayerPrefs.GetInt("HighScore", 0);.
  • Online Leaderboards:
    • For online leaderboards, you'll need to integrate with a backend service (e.g., Unity Gaming Services, PlayFab, Google Play Games, Apple Game Center) to store and retrieve scores from a server.

Best Practices for Scoreboard Implementation

  • Singleton Pattern: Using a singleton for your ScoreManager (as shown in the example) provides a globally accessible instance, making it easy for any script to update the score without needing a direct reference.
  • Separation of Concerns: Keep your score logic in a dedicated ScoreManager script. Don't mix it excessively with player movement or enemy AI.
  • UI Canvas Scale: Set your Canvas Scaler component's UI Scale Mode to Scale With Screen Size to ensure your scoreboard scales properly across different resolutions.
  • Clear Visibility: Ensure the score text has good contrast against the background and is large enough to be easily read by the player.

By following these steps, you can effectively implement a functional and engaging scoreboard in your Unity game, providing players with a clear measure of their achievements.