【Unity3d】WWW类发起web连接

初学unity3d,解决一个游戏与web服务器连接问题。

看了项目中原始代码,发现每次之前的程序员每次调用WWW类都需要写一遍StartCoroutine,然后各种重复代码。

于是写了一个简单的封装类,先记录下来,将来慢慢优化。

如何使用:

     WWWConnection connection = new WWWConnection(url, form);  //url: 地址   ,   form: WWWForm--Unity3d用于封装参数的类
	connection.connectionEvent += new WWWConnection.Callback(GetResult);  //注册回调方法
	StartCoroutine(connection.Get());  //启动网络连接

	void GetResult(WWWConnection connection)  //回调方法
	{
		Debug.Log(connection.content);
	}

  

using UnityEngine;
using System.Collections;

public class WWWConnection
{
	public WWWConnection(string url)
	{
		this.www = new WWW(url);
	}
	
	public WWWConnection(string url, WWWForm form)
	{
		this.www = new WWW(url, form);
	}
	
	private WWW www;
	
	public bool isDone{
		get{return IsDone();}
	}
	
	public float progress{
		get{return Progress ();}
	}
	
	public string content{
		get{return Content ();}
	}
	
	public delegate void Callback(WWWConnection connection);
	
	public event Callback connectionEvent;
	
	public IEnumerator Get()
	{
		yield return this.www;
		if(this.connectionEvent != null)
		{
			connectionEvent(this);
		}
	}
	
	private bool IsDone()
	{
		return this.www.isDone;
	}
	
	private float Progress()
	{
		return this.www.progress;
	}
	
	private string Content()
	{
		return this.www.text;
	}
	
	public WWW GetWWW()
	{
		return this.www;
	}
	
}

  

原文地址:https://www.cnblogs.com/LoadingChan/p/3370630.html