Unity C#委托进行AJAX调用

时间:2014-11-19 05:44:42

标签: c# unityscript

我正在使用C#开发一个Unity项目,并且知道WWW对象会对HTTP做类似的事情。但是,WWW不提供回调函数,因此我创建了自己的类来提供委托。

using UnityEngine;
using System.Collections;

public class WebAccess : MonoBehaviour {
    private WWW     www;

    public delegate void OnRspnReady(WebAccess webAccess);  // Response ready callback
    public delegate void OnRspnErr(WebAccess webAccess);    // Response error callback
    private void noOp(WebAccess webAccess){}    // no operation

    public WebAccess(){}

    // create a new customised request
    public  void    sendReq(string uri){
        this.sendReq(uri, noOp, noOp);
    }
    public  void    sendReq(string uri, OnRspnReady onRspnReady){
        this.sendReq(uri, onRspnReady, noOp);
    }
    public  void    sendReq(string uri, OnRspnReady onRspnReady, OnRspnErr onRspnErr){
        this.www = new WWW(uri);
        StartCoroutine(waitForReq(this.www, onRspnReady, onRspnErr));
        // return this.www.responseHeaders.ToString();
    }

    // get Response content
    public WWW  getWWW(){
        return this.www;
    }

    private IEnumerator waitTillDone(){
        while(!this.www.isDone){}
        yield return null;
    }

    private IEnumerator waitForReq(WWW www, OnRspnReady onRspnReady, OnRspnErr onRspnErr) {
        yield return www;

        // check for errors
        if (www.error == null){
            // Debug.Log("WWW Ok!: " + www.text);
            onRspnReady(this);
        } else {
            // Debug.Log("WWW Error: "+ www.error);
            onRspnErr(this);
        }  
    }
}

我使用以下代码尝试并得到一个积极的结果:     使用UnityEngine;     使用System.Collections;

public class Main : MonoBehaviour {

    // Use this for initialization
    void Start () {
        WebAccess  webAccess = GameObject.Find("Programs").transform.FindChild("WebAccess").GetComponent<WebAccess>();

        WebAccess.OnRspnReady fn = new WebAccess.OnRspnReady(rspnReadyCallBack);

        webAccess.sendReq("http://localhost", fn);
    }

    private void rspnReadyCallBack(WebAccess webAccess){
        Debug.Log(string.Concat("Main: ", webAccess.getWWW().text));
    }
}

由于我习惯用Javascript编程,创建独立的函数 rspnReadyCallBack ,有点麻烦。我的问题是 - 如何创建委托函数,因为我会在Javascript中进行回调? 例如,这个:

xmlhttp.onreadystatechange = function(){
 if (xmlhttp.readyState==4 && xmlhttp.status==200){
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
 }
}

0 个答案:

没有答案