Last active
July 20, 2017 13:30
-
-
Save ASPePeX/3c0bc2c2cb831ef2a0315ae9c50b5e38 to your computer and use it in GitHub Desktop.
Unity www poll script
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
public class InputJSON | |
{ | |
public float Input; | |
} |
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 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