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

bookScoring System

Swipe um das Menü anzuzeigen

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?

Wählen Sie die richtige Antwort aus

question mark

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

Wählen Sie die richtige Antwort aus

question mark

What is the purpose of PlayerPrefs in this script?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 5

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 4. Kapitel 5
some-alt