所以我在XNA上制作了一个游戏,并从文件中获得分数,我做了类似的事情......
private void GetScore()
{
if (File.Exists(scoreFilename))
{
using (StreamReader sr = new StreamReader(scoreFilename))
{
hiScore = Convert.ToInt16(sr.ReadLine());
}
}
else
{
FileStream fs = File.Create(scoreFilename);
fs.Close();
using (StreamWriter sw = new StreamWriter(scoreFilename))
{
sw.Write("0");
}
hiScore = 0;
}
}
这适用于Windows,但我如何为Android执行此操作?
答案 0 :(得分:0)
我认为你正在寻找IsolatedStorageFile。它应该与writing data on Windows Phone相同。您的新代码可能如下所示:
private void GetScore()
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists(scoreFilename))
{
var fs = store.OpenFile(scoreFilename, FileMode.Open);
using (StreamReader sr = new StreamReader(fs))
{
hiScore = Convert.ToInt16(sr.ReadLine());
}
}
else
{
var fs = store.CreateFile(scoreFilename);
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write("0");
}
hiScore = 0;
}
}
我没有对此进行过测试,并且可能有一种方法可以用更少的代码来完成,但我没有时间,所以我只更改了代码所需的最低数量。让我知道它是怎么回事。
答案 1 :(得分:0)
你也可以使用这样的外部目录:
定义用于存储上下文的类:
public class App
{
public static Context CurentContext { get; set; }
}
在主要活动上,初始化上下文:
public class Activity1 : Microsoft.Xna.Framework.AndroidGameActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
App.CurentContext = this;
var g = new Game1();
SetContentView((View)g.Services.GetService(typeof(View)));
g.Run();
}
}
然后访问外部目录:
var dirPath = App.CurentContext.GetExternalFilesDir(string.Empty).AbsolutePath;
string filePath = Path.Combine(dirPath, "YourScoreFileName.txt");
using (var stream = File.OpenRead(filePath))
{
}
该文件应存储在以下位置:
/storage/emulated/0/Android/data/[your_package]/files/