UnityTrafficSimulation/UnityProject/Assets/tweetPoller.cs

66 lines
1.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
[NetworkSettings(channel = 0, sendInterval = 1)]
public class tweetPoller : NetworkBehaviour {
public float updateInterval = 1;
private float timeSinceFetch = 0;
private int currentTweetCount = 0;
public string url = "http://localhost:8081";
public GameObject tweetPrefab;
private clientGameMenu client;
public override void OnStartServer ()
{
base.OnStartServer();
url = url.TrimEnd('/');
GameObject newTweetObject = Instantiate(tweetPrefab);
client = newTweetObject.GetComponent<clientGameMenu>();
NetworkServer.Spawn(newTweetObject);
}
// Update is called once per frame
void Update () {
if(isServer)
{
timeSinceFetch += Time.deltaTime;
if(timeSinceFetch > updateInterval)
{
timeSinceFetch = 0;
StartCoroutine("getTweetsBasedOnTweetCount");
}
}
}
IEnumerator getTweetsBasedOnTweetCount ()
{
using (WWW www = new WWW(url + "/tweetCount"))
{
yield return www;
int newTweetCount = int.Parse(www.text);
if (newTweetCount > currentTweetCount)
{
currentTweetCount = newTweetCount;
StartCoroutine("getTweets");
}
}
}
IEnumerator getTweets ()
{
using (WWW www = new WWW(url + "/tweets/last"))
{
yield return www;
client.RpcSetNewTweet(JsonUtility.FromJson<Tweet>(www.text));
}
}
}