Created
August 13, 2012 03:56
-
-
Save asus4/3336842 to your computer and use it in GitHub Desktop.
www request for unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
/// <summary> | |
/// Base WWW request component. | |
/// </summary> | |
public class WWWRequest : MonoBehaviour { | |
public enum Status { | |
SUCCESS, | |
ERROR | |
} | |
[SerializeField] | |
string url; | |
[SerializeField] | |
bool autoDestroy; | |
/// <summary> | |
/// Occurs when request complete. | |
/// </summary> | |
public event Action<WWWRequest> OnComplete; | |
WWW _www; | |
IEnumerator Start () | |
{ | |
if (Application.internetReachability == NetworkReachability.NotReachable) { | |
// network error | |
if (OnComplete != null) { | |
OnComplete (this); | |
} | |
return true; | |
} | |
_www = new WWW (url); | |
// TODO need time out error? | |
yield return _www; | |
// error check | |
if (!string.IsNullOrEmpty (_www.error)) { | |
status = Status.ERROR; | |
if (OnComplete != null) { | |
OnComplete (this); | |
} | |
} else { | |
status = Status.SUCCESS; | |
if (OnComplete != null) { | |
OnComplete (this); | |
} | |
} | |
if (autoDestroy) { | |
Destroy (gameObject); | |
} | |
} | |
void OnDestroy () | |
{ | |
if (_www != null) { | |
if (!IsDone && OnComplete != null) { | |
status = Status.ERROR; | |
OnComplete (this); | |
OnComplete = null; | |
} | |
_www.Dispose (); | |
_www = null; | |
} | |
} | |
#region Props | |
public WWW www { | |
get { return _www;} | |
} | |
public Status status { | |
get; | |
protected set; | |
} | |
public bool IsDone { | |
get { | |
if (_www == null) { | |
return false; | |
} | |
return _www.isDone; | |
} | |
} | |
public float Progress { | |
get { | |
if (_www == null) { | |
return 0f; | |
} | |
return _www.progress; | |
} | |
} | |
/// <summary> | |
/// date file created. | |
/// in response headers [DAT | |
/// </summary> | |
/// <value> | |
/// datetime. | |
/// </value> | |
public DateTime Date { | |
get { | |
if (!IsDone) { | |
return DateTime.MinValue; | |
} | |
return DateTime.Parse (_www.responseHeaders ["DATE"]); | |
} | |
} | |
#endregion | |
#region Builder | |
/// <summary> | |
/// Make the request | |
/// </summary> | |
/// <param name='url'> | |
/// URL. | |
/// </param> | |
public static WWWRequest Make (string url) | |
{ | |
GameObject go = new GameObject ("WWWRequest"); | |
WWWRequest req = go.AddComponent<WWWRequest> (); | |
req.url = url; | |
req.autoDestroy = true; | |
return req; | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
useful