Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Scoring System | Programming with C# - Extra Mechanics
Unity for Beginners

bookScoring System

Svep för att visa menyn

Score

The endless jumper is now progressively harder, but has no scoring system yet.

Tracking how high the player climbs, and trying to beat a previous record, is a core part of endless jumper games.

Let's add this inside the GameManager script.

Step 1: Create a Score Variable

We want a whole number score:

int score = 0;

It starts at 0.

We also need access to the player's height:

public Transform playerTransform;

Assign this in the Inspector.

Step 2: Update the Score

Inside Update(), we check each frame whether the player has climbed higher than the current score.

Pseudocode:

// If player Y position > score
// Update score

Code:

if(playerTransform.position.y > score)
{
score = (int)playerTransform.position.y;
print("score" + score * 10);
}

Key points:

  • the player's Y position is a float;
  • we cast it to an int using (int);
  • we multiply by 10 when printing to make the score look bigger (this does not change the stored value).

Step 3: Add a High Score

We want a high score that:

  • survives scene reloads;
  • persists after closing the game.

We use PlayerPrefs:

if (score > PlayerPrefs.GetInt("Highscore"))
{
PlayerPrefs.SetInt("Highscore", score);
print("Highscore" + PlayerPrefs.GetInt("Highscore") * 10);
}
  • "Highscore" is the save key;
  • GetInt() retrieves the saved value;
  • SetInt() stores a new one.

Now we have

  • a live climbing score;
  • a persistent high score;
  • replay motivation.

Later, we'll display this properly using Unity's UI system.

1. What does the line score = (int)playerTransform.position.y; do in the scoring system?

2. Why is the score multiplied by 10 in the print statement in the scoring system?

3. What is the purpose of PlayerPrefs in this script?

question mark

What does the line score = (int)playerTransform.position.y; do in the scoring system?

Vänligen välj det korrekta svaret

question mark

Why is the score multiplied by 10 in the print statement in the scoring system?

Vänligen välj det korrekta svaret

question mark

What is the purpose of PlayerPrefs in this script?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 5

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 4. Kapitel 5
some-alt