- Home /
Question by
mhunter1234 · Apr 26, 2016 at 01:28 PM ·
score systemfile-ioscoring
I'm having trouble reading and writing a text file. I am suppose to have it to where high scores and players initials are saved and displayed in my game.
public class hi : MonoBehaviour
{
public Text HighScoretext;
private string filepath;
List<Highscore> Scores;
void Start()
{
this.filepath = Path.Combine(Application.dataPath , "/" + "scores.txt");
if (File.Exists(filepath))
this.LoadScores();
this.Scores = new List<Highscore>();
}
private void LoadScores()
{
using (StreamReader sr = new StreamReader(Application.dataPath + "/score.txt"))
{
string ts = "";
ts = sr.ReadLine();
while (ts != null)
{
string[] values = ts.Split(',');
string initials =values [0];
int score= int.Parse( values[1]);
Highscore newscore = new Highscore(score, initials);
Scores.Add(newscore);
ts = sr.ReadLine();
}
}
}
public void UpdateScores(int score)
{
if (score > this.Scores[4].score)
{
// Read the initials and create a new highscore object and add it to the list // this.Scores.Add(score);
this.Scores = this.Scores.OrderByDescending(x => x).Take(5).ToList();
this.SavesScores();
}
}
//public void GetInitials(string a)
//{
// Scores.Add
//}
private void SavesScores()
{
using (StreamWriter we = new StreamWriter(Application.dataPath + "/score.txt"))
{
foreach( Highscore score in Scores)
{
we.WriteLine();
}
}
}
}
class Highscore : IComparable
{
public int score;
public string initials;
public Highscore(int s, string i)
{
score = s;
initials = i;
}
public int CompareTo(Highscore other)
{
return -1 * this.score.CompareTo(other.score);
}
public override string ToString()
{
return initials+","+score;
}
}
Comment
What is the problem you're having? You just pasted your script! From what I can see looking at the code you're checking for scores.txt but then trying to loads score.txt (spelt differently) which probably isn't what you intended..
Your answer
![](https://koobas.hobune.stream/wayback/20220612075639im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Scoring help ! 1 Answer
How to increase score by one per second when you are holding an object 2 Answers
How to make a scoreboard? 0 Answers