常用API
将鼠标坐标系转换为Camera的坐标系
Camera.main.ScreenToViewportPoint
禁用碰撞体、按钮禁用
GetComponent<BoxCollider> ().enabled = false;
小Tip
数据存储的方法
PlayerPrefs.SetInt();//保存整型数据
PlayerPrefs.SetFloat();//保存浮点型数据
PlayerPrefs.SetString();//保存字符串型数据
PlayerPrefs.GetInt();//读取整型数据
PlayerPrefs.GetFloat();//读取浮点型数据
PlayerPrefs.GetString();//读取字符串型数据
PlayerPrefs.SetInt("KEY","VALUE");
读取普通文本资源:TextAsset
TextAsset text=(TextAsset)Resources.Load("unity3d");
Debug.Log(text.text);
在Project窗口的根目录创建Resources
文件夹
然后把名字为unity3d.txt
的文件夹的文件放在Resources
文件夹下就可以读取到。
解析Json
需要第三方插件
下载网址:https://sourceforge.net/projects/litjson/
仅需要LitJson.dll
文件放在项目的Plugins
文件夹下
创建Json文件
using LitJson; //引用LitJson
void Json(){
//创建数据
JsonDate json = new JsonDate();
json["name"] = "皮皮虾";
json["sex"] = "男";
//转换JsonDate为Json文本
string strJson = json.ToJson();
//打印json
Debug.Log(strJson);
}
Json文件添加一行
using LitJson; //引用LitJson
void Json(){
//创建数据
JsonDate json = new JsonDate();
json["name"] = "皮皮虾";
json["sex"] = "男";
JsonDate json1 = new JsonDate();
//添加一行
json1.Add(json);
//转换JsonDate为Json文本
string strJson = json1.ToJson();
//打印json
Debug.Log(strJson);
}
上面两个都得到
[
{
"Name": "皮皮虾",
"sex": "男"
}
]
读取Json文件
using LitJson; //引用LitJson
void Json(){
//创建数据
JsonDate json = new JsonDate();
json["name"] = "皮皮虾";
json["sex"] = "男";
JsonDate json1 = new JsonDate();
//添加一行
json1.Add(json);
//转换JsonDate为Json文本
string strJson = json1.ToJson();
//转换Json文本为JsonDate
JsonData jsonData2 = JsonMapper.ToObject(strJson);
//打印jsonData2中name
Debug.Log(jsonData2["name"]);
}
转义编码
LitJson中编码为unicode,不支持中文,所以我们要把他转换为GBK
仅需要在转换JsonDate为Json文本后使用即可
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
var ss = reg.Replace(要转换的字符串, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });