public void SaveScore (int score)
{
List
//系统:Linq方法(using System.Linq;)
list.Sort((x, y) => (-x.CompareTo(y)));//调用List的Sort方法,从大到小对list进行排序[(-x)(从小到大改为x
bestScoreArr = list.ToArray();//将排好序的list转给数组
//50 20 10 加入传score为60,则将60排在低 bestScoreArr[0]
int index = -1;
for (int i = 0; i < bestScoreArr .Count() ; i++)
{
if (score >bestScoreArr [i])//score依次与数组中的数进行对比,当比一个数大时,记录这个数的索引将后面的数都向后移。
{
index = i;
}
}
if (index == -1) return;//score比数组中的值都小,不需保存,退出方法。
for (int i = bestScoreArr .Length -1; i >index ; i--)//从后向前将index之后的数据依次向后移
{
bestScoreArr[i] = bestScoreArr[i - 1];
}
bestScoreArr[index] = score;//将score填入空出位。
Save();//保存。
}
//获取最大值方法(Linq)
public int GetBestScore()
{
return bestScoreArr.Max();
}
//要存储的游戏数据类
public class GameDate
{
public static bool IsAgainGame =false ;
private bool isFirstGame;
private bool isMusicOn;
private int[] bestScoreArr;
public void SetBestScoreArr(int[] bestScoreArr)
{
this.bestScoreArr = bestScoreArr;
}
public int [] GetBestScoreArr()
{
return bestScoreArr;
}
//(其他......get;set方法省略)
private int selectSkin;
private bool[] skinUnlocked;
private int diamondCount;
}
/// <summary>
/// 储存数据
/// </summary>
private void Save()
{
try
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fs = File.Create(Application.persistentDataPath + "/DameData.data"))
{
data.SetBestScoreArr(bestScoreArr);
data.SetDiamondCount(diamondCount);
data.SetIsFirstGame(isFirstGame);
data.SetMusicOn(isMusicOn);
data.SetSelectSkin(selectSkin);
data.SetSkinUnlocked(skinUnlocked);
bf.Serialize(fs, data);
}
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
}
/// <summary>
/// 读取数据
///using System.Runtime.Serialization.Formatters.Binary;
///using System.IO;
/// </summary>
private void Read()
{
try
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fs = File .Open (Application.persistentDataPath + "/DameData.data",FileMode.Open ))
{
data = (GameDate )bf.Deserialize(fs);
}
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
}