还需要定义一些常量:
const int recordsPerPage = 5;
const string URL = "127.0.0.1:5000/scores";
定义一个数据结构:
public struct Data {
public int id;
public string name;
public int score;
}
在动手之前,还要了解两个东西:WWW类和LitJson库。WWW类是Unity自带的处理HTTP请求的类;LitJson是一个C#处理JSON的开源库。要使用LitJson,先从官网下载dll文件,然后导入Asset。
SaveLoad类的功能就像名字一样,包括保存Save和载入Load。
public void Save(Data data) { var jsonString = JsonMapper.ToJson(data); var headers = new Dictionary<string, string> (); headers.Add ("Content-Type", "application/json"); var scores = new WWW (URL, new System.Text.UTF8Encoding ().GetBytes (jsonString), headers); StartCoroutine (WaitForPost (scores)); } IEnumerator WaitForPost(WWW www){ yield return www; Debug.Log (www.text); } |
这里创建WWW实例,指定了URL、header和提交数据。第一行的JsonMapper可以在对象和JSON之间进行转换,前提是对象中的属性和JSON中的键要保持一致。
public void Load() { var scores = new WWW (URL); StartCoroutine(WaitForGet(scores)); } IEnumerator WaitForGet(WWW www){ yield return www; if (www.error == null && www.isDone) { var dataList = JsonMapper.ToObject<DataList>(www.text); data = dataList.data; }else{ Debug.Log ("Failed to connect to server!"); Debug.Log (www.error); } } |
Load方法中是将前面index方法返回的JSON文本转换成对象,这里为了实现转换,新建一个DataList类,其中的属性是List<Data>。
到这里,客户端的读取和保存数据就实现了。其余的逻辑,比如和UI的交互,在这里就不写了。感兴趣的可以看我的小游戏的完整代码。GitHub传送门
最后谈谈部署的事情。如果要部署到SAE有几点要注意:
代码要进行一定的修改以适应MySQLdb。
要注意中文的编码。如用unicode方法转换名字属性,以及文件头部的:
# -*- coding:utf8 -*-
#encoding = utf-8
最后说说比较坑的Unity跨域访问的限制。在我成功部署后,curl测试没有问题了。结果Unity报了错:
SecurityException: No valid crossdomain policy available to allow access
经过一番搜索,原来要在服务器的根目录增加一个crossdomain.xml文件。文件内容大致如下:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
但是SAE好像不支持上传文件到根目录。只能用Flask仿冒一下了:
@app.route('/crossdomain.xml')
def fake():
xml = """上面的那堆内容"""
return xml, 200, {'Content-Type': 'text/xml; charset=ascii'}