Skip to content

Instantly share code, notes, and snippets.

@liortal53
Last active July 9, 2016 22:05
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save liortal53/280998ff87141980b98a to your computer and use it in GitHub Desktop.
Workaround for a Unity bug with yielding a WWW object on iOS with no network connectivity
using System.Collections;
using UnityEngine;
/// <summary>
/// Wrapper around Unity's WWW request class.
/// </summary>
public class WWWRequest : IEnumerator
{
/// <summary>
/// The default timeout for requests (in seconds).
/// </summary>
private const float DEFAULT_TIMEOUT_SECONDS = 30f;
private WWW wwwRequest;
private float timeout;
private float requestDuration;
/// <summary>
/// Gets a value indicating whether this ongoing WWW request completed successfully.
/// This should can be tested after yielding on this instance to check the request completed successfully.
/// </summary>
public bool Completed
{
get { return isDone && string.IsNullOrEmpty(wwwRequest.error); }
}
public string url
{
get { return wwwRequest.url; }
}
public string error
{
get { return wwwRequest.error; }
}
/// <summary>
/// Gets a value indicating whether this request is done or not.
/// </summary>
public bool isDone
{
get { return wwwRequest.isDone; }
}
public string text
{
get { return Completed ? wwwRequest.text : null; }
}
/// <summary>
/// Initializes a new instance of the <see cref="WWWRequest"/> class.
/// </summary>
public WWWRequest(WWW wwwRequest)
: this(wwwRequest, DEFAULT_TIMEOUT_SECONDS)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WWWRequest"/> class.
/// </summary>
public WWWRequest(WWW wwwRequest, float timeout)
{
if (wwwRequest == null)
{
throw new System.ArgumentNullException("wwwRequest");
}
this.wwwRequest = wwwRequest;
this.timeout = timeout;
}
#region IEnumerator implementation
public bool MoveNext ()
{
requestDuration += Time.deltaTime;
return !wwwRequest.isDone && requestDuration <= timeout;
}
public void Reset ()
{
wwwRequest = null;
requestDuration = 0f;
timeout = 0f;
}
public object Current
{
get
{
return null;
}
}
#endregion
}
@OJ3D
Copy link

OJ3D commented Jul 9, 2016

@liortal53 - This looks awesome. I've been having this bug on ios with my app for sometime.
How do I go about using this script ( i'm a unity noob). I'm not quite sure.

  1. Do I just load it into a c# script, Set it in my files, and forget it?
  2. or do I have to place it on a gameobject and call it as follows:
    www mysite = new www ("www.google.com") <--this is the www method
    yield return mysite;
    instead --
    wwwrequest mysite = new wwwrequest ("www.google.com") <-- not sure if your method is something like this
    yield return mysite
    ??
    An example would be awesome.
    Thanks again for the share.

OJ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment