最近想用txt來做安卓遊戲的地圖配置,寫了很久都不對。。於是乎。。。
using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine.UI;
public class CanSeleteGame : MonoBehaviour
{
public GameObject lable;
private string strTxt;
void Awake()
{
}
string path = "";
// Use this for initialization
void Start()
{
if (Application.platform == RuntimePlatform.Android)
{
path = Application.persistentDataPath;
}
else if (Application.platform == RuntimePlatform.WindowsPlayer)
{
path = Application.dataPath;
}
else if (Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath;
}
strTxt = LoadFile(path, "t.txt");
if (strTxt != "error")
{
lable.GetComponent<UILabel>().text = "read:" + strTxt;
}
else
{
createORwriteConfigFile(path, "t.txt", "111000000000000000000000000000000000000000000000000000000000");
string str = LoadFile(path, "t.txt");
lable.GetComponent<UILabel>().text = "create:" + str;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
//WriteIn("100");
string str = LoadFile(path, "t.txt");
lable.GetComponent<UILabel>().text = "REad:" + str;
}
}
/// <summary>
/// 在指定位置創建文件 如果文件已經存在則追加文件內容
/// </summary>
/// <param name='path'>
/// 路徑
/// </param>
/// <param name='name'>
/// 文件名
/// </param>
/// <param name='info'>
/// 文件內容
/// </param>
private void createORwriteConfigFile(string path, string name, string info)
{
StreamWriter sw;
FileInfo t = new FileInfo(path + "//" + name);
if (!t.Exists)
{
sw = t.CreateText();
}
else
{
sw = t.AppendText();
}
sw.WriteLine(info);
sw.Close();
sw.Dispose();
}
private void WriteIn(string content)
{
FileStream fs = new FileStream(path + "//" + "t.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(content);
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
}
/// <summary>
/// 刪除文件
/// </summary>
/// <param name='path'>
/// Path.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
void DeleteFile(string path, string name)
{
File.Delete(path + "//" + name);
}
/// <summary>
/// 讀取文件內容 僅讀取第一行
/// </summary>
/// <param name='path'>
/// Path.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
private string LoadFile(string path, string name)
{
FileInfo t = new FileInfo(path + "//" + name);
if (!t.Exists)
{
return "error";
}
StreamReader sr = null;
sr = File.OpenText(path + "//" + name);
string line;
while ((line = sr.ReadLine()) != null)
{
break;
}
sr.Close();
sr.Dispose();
return line;
}
}
注意:各個平臺的文件存放位置不同。
2.. Application.persistentDataPath;這個路徑只能在程序運行時纔可以做操作,也就是說,在程序沒有運行時,將文件放在這個路徑中是無效的(好坑爹 = =)