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

bookScoring System

Deslize para mostrar o menu

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?

Selecione a resposta correta

question mark

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

Selecione a resposta correta

question mark

What is the purpose of PlayerPrefs in this script?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 5

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 4. Capítulo 5
some-alt