平时做项目,代码中是不允许出现硬代码的,一般我们是怎么处理的呢? 那么硬代码又是什么呢?
我们俗称的硬代码:eg: public UIlabel label; label.text = “欢迎来到梦幻岛”; 这样我们俗称为硬代码。
好了,那么该如何避免,话不多说,直接上图:
这是一种处理方式,TXT 格式的文档,前面是ID,后面是描述性文字。
可是我们该如何在项目中访问这个txt文件里面的数据呢? 话不多说,直接上代码:
using UnityEngine;
using System.Collections; public class ReadTxt :MonoBehaviour{ public TextAsset txt;
public static ReadTxt _instance;
string fonttxt;
void Awake()
{
_instance = this;
} void Start() { } public string GetFont(int ID)
{
string[] taskinfoArray = txt.ToString().Split('\n');
foreach(string str in taskinfoArray){ string[] Fontlist = str.Split('|');
int id = int.Parse(Fontlist[]);
while (ID== id) {
fonttxt = Fontlist[];
break;
}
} return fonttxt;
} }
上述用到了单利,单利这里我们就不赘述了。
string[] taskinfoArray = txt.ToString().Split('\n'); 这里有些朋友就要问了,Split('\n')是干什么的,它是分割函数,检测是否有换行操作,如果有换行我们把它存在数组里面,
上面的txt文档,我们就是写完一行,肯定要回车换行写下一句,这里就是用这个Split()函数进行检测的。
好了说到这里,想必大家都清楚了吧。至于调用呢,这个就很简单了。
using UnityEngine;
using System.Collections; public class TestTxt : MonoBehaviour { public UILabel label; void Start()
{
string bbb = ReadTxt._instance.GetFont(); label.text = bbb;
} }
然而label显示的 文字必定是:维护公告。 这里我们只是抛砖引玉,所以写的比较粗糙,望大家谅解。