- Home /
Huge Lag Spikes on using (WebClient webClient)
Hello, I am trying to get a live ethereum price variable for my game. It works fine but I get lag spikes everytime it updates (every 2 seconds).
Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.Text;
using System.Net;
using System;
public class EthereumPrice : MonoBehaviour {
public Text ethPriceText;
public float time = 0;
public void Start() {
StartCoroutine(Example());
}
public void Update() {
time += Time.deltaTime;
if (time >= 1) {
StartCoroutine(Example());
time = 0;
}
}
IEnumerator Example()
{
yield return new WaitForSecondsRealtime(1f);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
var json = n.DownloadString("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
string valueOriginal = Convert.ToString(json);
json = json.Replace("{\"USD\":", string.Empty);
json = json.Replace("}", string.Empty);
var sStrings = json.Split();
float ethPrice = float.Parse(sStrings[0]);
ethPriceText.text = "Ethereum ($" + ethPrice + ")";
time += Time.deltaTime;
Debug.Log (json);
}
}
}
What the codes does is download the string from the JSON url and sets "json" to "{"USD":6790.55}". Then I use float.parse to take out the "{"USD":" and the "}" so I have 6790.55 left over. I then set this string as a float into a seperate variable. But for some reason I get massive lag spikes everytime it runs the Coroutine. Does anyone have any ideas?
Still need an answer asap, this is for a school project due in 2 weeks :/ Still can't figure it out other than making it refresh every $$anonymous$$ute or so.
Answer by Cynikal · Apr 05, 2018 at 07:49 PM
If the lag spike is happening on download, then the server is most likely holding you up. The best bet would be to convert it to an async operation. It'll take some reformatting of your code, but you'll get the results without any hesitation.
Alright, do you, in fact, have any knowledge of async? I have never used or heard of it before and I am not sure where to start.
Your answer
Follow this Question
Related Questions
Random lag spikes any time processor intensive tasks a scene 0 Answers
Multiple Cars not working 1 Answer
Reference Variables and Drag-And-Drop 0 Answers
Reference Variables and Drag-And-Drop 0 Answers