Tracking Player Scores and Level Progress

This page describes how the ObservedTextFile class can be used to create a player progress system.

In this example, we will show how the ObservedTextFile class can be used to track player scores and level progress in a game. This can be useful when we need to persist the data and track changes in real-time.

We will start by creating an instance of ObservedTextFile for each player, with the file path set to the player's name. This will allow us to have a separate file for each player's score and progress data.

var player1File = new ObservedTextFile("player1.txt");
var player2File = new ObservedTextFile("player2.txt");

Next, we will define a callback method that will be notified when the score or level progress of a player changes. This method will take the current text of the file as a parameter and update the UI accordingly.

void UpdateUI(string text, WatcherChangeTypes changeType)
{
    // Parse the text and update the UI
    var parts = text.Split(',');
    var score = int.Parse(parts[0]);
    var level = int.Parse(parts[1]);

    // Update the UI with the new score and level
    scoreText.text = score.ToString();
    levelText.text = level.ToString();
}

Next, we will subscribe to the ObservedTextFile instance for each player, so that the UpdateUI method is called whenever there is a change to the player's file.

player1File.Subscribe(UpdateUI);
player2File.Subscribe(UpdateUI);

Now, whenever a player's score or level changes, the UpdateUI method will be called and the UI will be updated with the new data. To write to the file, we can use the WriteAllText or AppendText methods of the ObservedTextFile class.

void UpdatePlayerScore(int playerId, int score)
{
    var file = playerId == 1 ? player1File : player2File;
    var text = file.ReadAllText();
    var parts = text.Split(',');
    var currentScore = int.Parse(parts[0]);
    var level = int.Parse(parts[1]);
    file.WriteAllText($"{currentScore + score},{level}");
}
void UpdatePlayerLevel(int playerId, int level)
{
    var file = playerId == 1 ? player1File : player2File;
    var text = file.ReadAllText();
    var parts = text.Split(',');
    var score = int.Parse(parts[0]);
    file.WriteAllText($"{score},{level}");
}

This example demonstrates how the ObservedTextFile class can be used to track player scores and level progress in a game. By using this class, we can persist the data to disk and update the UI in real-time whenever there is a change to the data.

Last updated