写这个是因为想把 txt文件当成配置文件,即一对一,类似键值对一样存取信息
1. txt保存在StreamingAssets文件夹下 一 一 对应,用逗号分隔
2.代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class TxtHandle : MonoBehaviour {
public static string[] configAry;
string txtName = "configuration.txt";
// Use this for initialization
void Start () {
//StartCoroutine(WWWLoadTxtFile("/" + txtName));
IOLoadTxtFile(txtName);
}
/// <summary>
/// 文件流读取Txt文件
/// </summary>
/// <param name="_filePath"></param>
void IOLoadTxtFile(string _filePath)
{
//本地路径
var fileAddress = System.IO.Path.Combine(Application.streamingAssetsPath, _filePath);
FileInfo fInfo0 = new FileInfo(fileAddress);
string s = "";
if (fInfo0.Exists)
{
StreamReader r = new StreamReader(fileAddress);
s = r.ReadToEnd();
configAry = s.Trim().Split(',');
SceneManager.LoadScene(1);
Debug.Log(s);
}
}
/// <summary>
/// www类 加载txt文件
/// </summary>
/// <param name="_filePath"></param>
/// <returns></returns>
public IEnumerator WWWLoadTxtFile(string _filePath)
{
print(Application.streamingAssetsPath);
WWW www = new WWW(Application.streamingAssetsPath + _filePath);
yield return www;
if (www.error == null)
{
configAry = www.text.ToString().Trim().Split(',');
foreach (var item in configAry)
{
print(item);
}
SceneManager.LoadScene(1);
}
else
{
Debug.Log(www.error);
}
}
/// <summary>
/// 根据传过来的 string 返回 该字符串在txt文件中的下一个字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string TxtReadStr(string str)
{
string tempStr = null;
for (int i = 0; i < TxtHandle.configAry.Length; i++)
{
if (TxtHandle.configAry[i].Trim().Equals(str, StringComparison.CurrentCulture))
{
tempStr = TxtHandle.configAry[i + 1];
break;
}
}
return tempStr;
}
}
3. 用法示例:
m_ipAddress = TxtHandle.TxtReadStr("serverIP");
m_port = int.Parse(TxtHandle.TxtReadStr("port"));
print(" ---------------->ip" + m_ipAddress + "port" + m_port);
4.结果如下: