- Home /
Question by
mhunter1234 · May 01, 2016 at 04:38 PM ·
scorescore systemfile-ioscoreboard
I need my script to load and save my players score to a text file . When I attach the script to a gameobject the script either is not found or it just prints 5,4,3,2,1 or all )0's.
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 HighScores : MonoBehaviour
{
private int highscore;
public Text HighScoretext;
private string filepath;
public List<Highscore> Scores { get; private set; }
void Start()
{
this.filepath = Path.Combine(Application.dataPath, "/" + "score.txt");
if (File.Exists(filepath))
this.LoadScores();
this.Scores = new List<Highscore>();
highscore = this.Scores[4].score;
}
void LoadScores()
{
int i = 0;
StreamReader sr = null;
try
{
sr = new StreamReader(Application.dataPath + "/" + "score.txt");
string info = sr.ReadLine();
if (info == null)
{
throw new FileNotFoundException();
}
while (info != null)
{
string[] myinfo = info.Split(',');
// string initials = myinfo[0];
//int score = int.Parse(myinfo[1]);
Scores.Add(new Highscore(int.Parse(myinfo[1]), myinfo[0]));
info = sr.ReadLine();
i++;
}
}
catch (FileNotFoundException fnfe)
{
if (sr != null)
sr.Close();
Debug.Log("File not Found..." + fnfe.Message);
createFile();
}
catch (Exception e)
{
Debug.Log("File not found ..." + e.Message);
if (sr != null)
sr.Close();
createFile();
}
finally
{
if (sr != null)
sr.Close();
}
}
private void createFile()
{
StreamWriter sw2 = new StreamWriter(Application.dataPath + "/" + "score.txt");
List<int> highscores = new List<int>();
highscores.Add(5);
highscores.Add(4);
highscores.Add(3);
highscores.Add(2);
highscores.Add(1);
foreach (int p in highscores)
sw2.WriteLine(p);
sw2.Close();
}
public void UpdateScores(int score)
{
if (score > this.Scores[4].score)
{
highscore = score;
this.Scores = this.Scores.OrderByDescending(x => x).Take(5).ToList();
this.SavesScores();
}
}
private void SavesScores()
{
using (StreamWriter we = new StreamWriter(Application.dataPath + "/score.txt"))
{
foreach (Highscore score in Scores)
{
we.WriteLine();
}
}
}
}
public struct 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
Your answer
Follow this Question
Related Questions
How to save score for survival time? 1 Answer
How to create a HighScore using playerprefs based on passed time? 1 Answer
Scoring System 3 Answers