Hi there,
I am trying to make a game and need a score system.
The error i get is: InvalidOperationException: ScoreData cannot be serialized because it does not have a default public constructor
And my code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using UnityEngine.UI;
using System;
public class scoresSaver : MonoBehaviour {
public static ScoreList scorelist;
public GameObject HighScoreText;
public Transform parent;
public GameObject text;
public static List<ScoreData> scores = new List<ScoreData>();
void Start()
{
LoadScores();
}
public static void AddScore(string nameIn, int scoreIn)
{
XmlSerializer serializer = new XmlSerializer(typeof(ScoreList));
FileStream stream = new FileStream(Application.dataPath + "/StreamingAssets/highscores.xml", FileMode.Open);
scorelist = serializer.Deserialize(stream) as ScoreList;
foreach (ScoreData score in scorelist.scores)
{
scores.Add(score);
}
scores.Add(new ScoreData(nameIn, scoreIn));
}
public void LoadScores()
{
XmlSerializer serializer2 = new XmlSerializer(typeof(ScoreList));
FileStream stream2 = new FileStream(Application.dataPath + "/StreamingAssets/highscores.xml", FileMode.Open);
scorelist = serializer2.Deserialize(stream2) as ScoreList;
foreach (ScoreData score in scorelist.scores)
{
scores.Add(score);
}
scores.Sort();
scores.Reverse();
stream2.Close();
foreach (ScoreData score in scores)
{
print(score.Name);
print(score.Score);
text = Instantiate(HighScoreText);
text.transform.SetParent(parent);
text.GetComponent<Text>().text = score.Name + ": " + score.Score;
}
}
}
[System.Serializable]
public class ScoreData : IComparable<ScoreData>
{
public string Name;
public int Score;
public ScoreData(string newName, int newScore)
{
Name = newName;
Score = newScore;
}
public int CompareTo(ScoreData other)
{
if (this.Score > other.Score)
return 1;
else if (this.Score < other.Score)
return -1;
else
return 0;
}
}
[System.Serializable]
public class ScoreList
{
public List<ScoreData> scores = new List<ScoreData>();
}
I hope someone can help.
Many Thanks