using UnityC# // I have to make a high score system that reads and writes a play
ID: 3694398 • Letter: U
Question
using UnityC#
// I have to make a high score system that reads and writes a players initals and score to a text file. Can you help me fix my code.
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using UnityEngine.UI;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.SocialPlatforms.Impl;
using System.Collections.Generic;
using System.Linq;
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<Highscore>
{
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;
}
}
Explanation / Answer
ScoreManager.cs
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.