Trabla: Unity3D: save scores into file example
Solving:
This example class loads scores from text file
First line of text file - current score user last have
Second line of text file - best score.
Example usage:
ResultsManager.Load(); // load data from file if exists,
// if not init with default values
int curretnScore = ResultsManager.GetCurrentScore();
int bestScore = ResultsManager.GetBestScore();
//Set score - if score is higher than best score - best score will be updated
ResultsManager.SetScore( 100 );
ResultsManager.Save(); // saving data to file
Example content of my-app_scores.txt:
15
210
using UnityEngine;
using System.Collections;
using System.IO;
public class ResultsManager {
static string filePath = Application.persistentDataPath + "/my-app_scores.txt";
static int currentScore = 0;
static int bestScore = 0;
public static void LoadScores (){
// Load scores from file
// First line - current score
// Second - best score
if (File.Exists (ResultsManager.filePath)) {
string[] scores = File.ReadAllLines ( ResultsManager.filePath );
if( scores.Length == 2 ){
//1. Current Score
ResultsManager.currentScore = int.Parse(scores[0]);
//2. Best Score
ResultsManager.bestScore = int.Parse(scores[1]);
}
}
}
public static int GetCurrentScore(){
return ResultsManager.currentScore;
}
public static int GetBestScore(){
return ResultsManager.bestScore;
}
public static void SetScore( int newScore ){
if( newScore > ResultsManager.bestScore ){
ResultsManager.bestScore = newScore;
}
ResultsManager.currentScore = newScore;
}
public static void SaveScores(){
// Saves currentScore and best Score
// into file
// first line - current score int
// second line - best score
string[] scores = new string[2];
//1. Current Score
scores[0] = ResultsManager.currentScore.ToString();
//2. Best Score
scores[1] = ResultsManager.bestScore.ToString();
File.WriteAllLines( ResultsManager.filePath, scores );
}
}
No comments:
Post a Comment