Unity結合Flask實現排行榜功能(3)

發表于:2015-04-01來源:uml.org.cn作者:娃娃點擊數: 標簽:Unity
public void Save(Data data){var jsonString = JsonMapper.ToJson(data);var headers = new Dictionarystring, string ();headers.Add (Content-Type, application/json);var scores = new WWW (URL, new System.Te

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。

  到這里,客戶端的讀取和保存數據就實現了。其余的邏輯,比如和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'}

原文轉自:http://www.uml.org.cn/Test/201503235.asp

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97