Skip to content

Instantly share code, notes, and snippets.

@ASPePeX
Last active July 20, 2017 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ASPePeX/3c0bc2c2cb831ef2a0315ae9c50b5e38 to your computer and use it in GitHub Desktop.
Save ASPePeX/3c0bc2c2cb831ef2a0315ae9c50b5e38 to your computer and use it in GitHub Desktop.
Unity www poll script
public class InputJSON
{
public float Input;
}
using System.Collections;
using System.Diagnostics;
using UnityEngine;
using Newtonsoft.Json;
public class InputPoll : MonoBehaviour
{
const string url = "http://192.168.1.92/stuff.json";
private bool _coroutineStatus = false;
private float _inputStatus;
private Stopwatch stopwatch;
private float _lastExecuteTime;
public float TimeBetweenExecutions = 0.5f;
void Start()
{
stopwatch = new Stopwatch();
}
void Update()
{
if (!_coroutineStatus)
{
_coroutineStatus = true;
StartCoroutine(Poll(TimeBetweenExecutions - _lastExecuteTime /1000));
}
}
IEnumerator Poll(float waitTime)
{
yield return new WaitForSecondsRealtime(waitTime);
StartCoroutine(DoPoll());
}
IEnumerator DoPoll()
{
stopwatch.Restart();
WWW www = new WWW(url);
yield return www;
_inputStatus = JsonConvert.DeserializeObject<InputJSON>(www.text).Input;
www.Dispose();
_coroutineStatus = false;
stopwatch.Stop();
_lastExecuteTime = stopwatch.ElapsedMilliseconds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment