In game development, a scoring system plays an extremely important role in providing feedback, making a player’s experience much more interesting, and stimulating competition. Whether it is going to be a platformer or a puzzle game, or maybe a shooter, adding the score system to your game is always worth it, for this can significantly improve the overall gaming experience. Let me guide you through creating a rather simple but efficient score system within Unity.
Packed with valuable insights, practical coding examples, and implementation strategies, this article is here to get your score system working, efficient, and ready for that great Unity project you’ve always wanted.
Why Scoring Systems are Important
Scores have different purposes in games: such as:
- Player Motivation: Giving players goals to reach, like high scores or achievements.
- Tracking Progress: It records how far the players have reached in the game or what kind of milestone they have achieved.
- Competition: This encourages competitive gameplay-from local high scores to online leaderboards.
A scoring system can be as simple or as complex as required. In this walkthrough, we’re going to build a basic score system that updates in real time, shows on screen, and saves between levels and scenes.
Step 1: Setting Up a New Unity Project
First of all, we will install Unity. Open Unity Hub and create a new 2D or 3D game project depending on your necessity.
- Open the Unity Hub, then click on “New Project.”
- Select 2D or 3D depending on your game.
- Name your project something like “SimpleScoreSystem.”
- Set project location and then click on Create.
Now you have set up your project; now, let us start building the score system.
Step 2: Creating the Score Script
We write a script that manages the player’s score. To keep things neat, this script will contain an increment and display for score and reset or save where possible.
Creating the Score Script
- In the Project window, select New Folder > Scripts
- Right-click inside this folder and choose Create > C# Script
- We’re going to call this one ScoreManager
Open the script and add the following code:
using UnityEngine; using UnityEngine.UI; public class ScoreManager : MonoBehaviour { public static int score; // Store the player's score public Text scoreText; // Reference to the UI text component void Start() { score = 0; // Initialize score UpdateScoreUI(); // Update the UI with the initial score } public void AddPoints(int points) { score += points; // Add points to the score UpdateScoreUI(); // Update the UI every time the score changes } void UpdateScoreUI() { scoreText.text = "Score: " + score.ToString(); // Display the score in the UI } }
Explanation:
- score: The player’s score, accessible from anywhere because it is static.
- scoreText: A reference to the UI Text object that will display the score.
- AddPoints(): This function is called whenever you want to add points to the score.
- UpdateScoreUI(): This updates the score display on the screen.
Step 3: Set Up the UI for the Score Display
- Now we’re going to set up a UI Text element that will display the score on-screen.
- Select Hierarchy and right-click it on the editor. Now go to UI > Text.
- The Canvas object along with a Text object is added. Change the text object to “ScoreText.”
- You can modify the font, size, position, and color to style your game. You can place the text in the top corner of the screen for a standard score placement.
- Select your ScoreManager script in the Inspector and drag the ScoreText object into the scoreText field of the script.
The score will now be shown on screen and updated in-game.
Step 4: Incrementing the Score
To do this you will need to cause score increases based on in game events such as when the player collects coins, defeats enemies or completes tasks.
For the sake of simplicity, let’s consider an example wherein points are collected upon gathering an item.
- Create a new script named CollectibleItem.
- Add this code to handle the collision event when the player collects the item:
using UnityEngine; public class CollectibleItem : MonoBehaviour { public int points = 10; // Points the item gives when collected void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("Player")) { // Add points to the score when the player collects the item FindObjectOfType<ScoreManager>().AddPoints(points); Destroy(gameObject); // Remove the item after it’s collected } } }
Explanation:
- This script assumes that there is a tag on the player called “Player”.
- When the player collides with an object like a coin, it invokes the function AddPoints() to add points.
- The line Destroy(gameObject) removes the item from the scene after it gets collected.
Make sure that your collectible object has 2D collider enabled to “Is Trigger” and a tag as “Player” set up for proper detection.
Step 5: Saving the Score Between Levels
Typically, many games require the score to persist between levels or scenes. Save the score by using PlayerPrefs of Unity, or use a singleton pattern.
For now, let’s use PlayerPrefs for simplicity.
Modify the Start method of the ScoreManager script to load the saved score when a new level starts:
void Start() { score = PlayerPrefs.GetInt("PlayerScore", 0); // Load saved score UpdateScoreUI(); // Update the UI with the loaded score } void OnDestroy() { PlayerPrefs.SetInt("PlayerScore", score); // Save the score when the level ends }
And now, the score will be saved between levels and loaded when the player starts a new level. To have the score reset to zero on a new game, you clear the saved data with PlayerPrefs.DeleteKey(“PlayerScore”);.
Step 6: Customizing the Score System for Your Game
Of course, every game is different so don’t be afraid to customize the score system to your hearts desire.
- Varying the Point Value: You can vary the points based on each activity that the player does in the game, for example, rare item collection or the killing of the tougher enemies.
- Combo Multiplier: Award combo multiplier to experienced players for performing successful actions in a string.
- Time-Based Scoring: Award more points for completing a level the sooner the player completes it.
For instance, when the multiplier would be added, it is nothing but simple modification of the AddPoints() function by incorporating the multiplier variable.
public void AddPoints(int points, float multiplier) { score += Mathf.RoundToInt(points * multiplier); // Apply multiplier to points UpdateScoreUI(); }
Now you can pass a multiplier when calling AddPoints()
, making it flexible for different gameplay scenarios.
Step 7: Optimization Testing
Test your scoring system across various levels to ensure it functions correctly:
Gameplay Integration: Check that the score increments properly during gameplay, especially in complex events like boss fights or power-up activations.
Performance: Ensure the score updates in real-time without frame drops.
UI Clarity: Make sure the score is always visible and easy to read.
Once you are confident that your system does what you intend it to do, you can add things like online leaderboards and high scores and so much more.
Conclusion
What you’re doing here for a simple score system in Unity is actually a much better way of enhancing your game and will give much more to your players in experience. You’ll learn exactly how scoring functions so that you can apply anything from simple points collection to complex, multi-faceted score systems wherein the reward is given to the skilled players. This guide arms you with the knowledge to actually create your own scoring system, with the flexibility to make improvements later on.
For the very adventurous, you might want to even add sharing bonus scores on social media or combo multipliers for rewards. The more times you iterate the system over your scores the more value and enjoyment you can transfer over to your players.
Happy coding, and best regards to you with your game development venture!