Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Events;
- using System.Collections;
- public class WWWHelper : MonoBehaviour // Must inherit from Monobehaviour to run coroutines
- {
- private static WWWHelper _instance; // there must be an instance of the class.
- // since it derives from MonoBehaviour it must also be added to a gameObjct as a component.
- private const float TIMEOUT = 5f; // a timeout if we need it.
- public const string TIMEOUT_RESPONSE = "TIMEOUT";
- public const string ERROR_PREFIX = "ERROR - ";
- // convenience method for easy access
- public static void MakeRequest(string url, UnityAction<string> callback)
- {
- if (_instance == null)
- {
- // create a game object to put this script on
- GameObject go = new GameObject("WWWHelper");
- // add this script to it and store it in _instance
- _instance = go.AddComponent<WWWHelper>();
- }
- _instance.StartCoroutine(_instance.RequestCoroutine(url, callback));
- }
- // Since coroutines cannot return a value, we usually use callbacks / delegates / actions
- private IEnumerator RequestCoroutine(string url, UnityAction<string> callback)
- {
- WWW request = new WWW(url);
- float timer = 0;
- while (timer < TIMEOUT)
- {
- timer += Time.deltaTime; // increment our timer every frame
- if (request.isDone) // if the request is done, no need to wait
- break;
- yield return new WaitForEndOfFrame(); // wait for the frame to complete before continuing this loop
- }
- string response = TIMEOUT_RESPONSE;
- if (request.isDone)
- {
- if (!string.IsNullOrEmpty(request.error))
- response = request.error;
- else
- response = request.text;
- }
- if (callback != null)
- callback.Invoke(response); // finally call the callback so we can hear about the response.
- }
- }
- public class Example : MonoBehaviour
- {
- private void Start()
- {
- WWWHelper.MakeRequest("www.naplandgames.com", HandleResponse);
- }
- private void HandleResponse(string response)
- {
- if (response == WWWHelper.TIMEOUT_RESPONSE)
- {
- Debug.LogError("Hey user, the response timed out, your internet sucks");
- }
- else if (response.Contains(WWWHelper.ERROR_PREFIX))
- {
- Debug.LogError("Hey developer, your requested URL stunk, here's the error: " + response);
- }
- else
- {
- Debug.Log("Hey user, here's the response: " + response);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement