/// <summary> /// Requests an energy recharge for our avatar to the server. /// The data returned indicates how much energy was restored. /// </summary> /// <param name="locationId"></param> /// <param name="onSuccess">The callback invoked when the call returns successfully</param> /// <param name="onError">The callback invoked if the call fails</param> /// <returns>An enumerator for the coroutine</returns> /// <exception cref="Exception">Exception when location id is invalid</exception> public IEnumerator PostRechargingStation( string locationId, Action <EnergyData> onSuccess, Action <string> onError) { if (string.IsNullOrEmpty(locationId)) { throw new System.Exception("Invalid Location Id!"); } string json = ""; using (UnityWebRequest webRequest = new UnityWebRequest(SERVER_URL + "/energystation/" + GetUserId() + "/" + locationId, "POST")) { if (!string.IsNullOrEmpty(json)) { byte[] bodyRaw = Encoding.UTF8.GetBytes(json); webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw); } webRequest.downloadHandler = new DownloadHandlerBuffer(); webRequest.SetRequestHeader("Content-Type", "application/json"); yield return(webRequest.SendWebRequest()); if (webRequest.isNetworkError || webRequest.isHttpError) { onError(webRequest.error); } else { if (webRequest.responseCode != 204) { EnergyData data = JsonMapper.ToObject <EnergyData>(webRequest.downloadHandler.text); onSuccess(data); } else { // Station recharging onSuccess(null); } } } }
/// <summary> /// Triggered when the server request to refill the player's energy returns successfully. /// This code starts the respawn on the energy station. /// </summary> /// <param name="data"></param> private void OnSuccess(EnergyData data) { IsLoading = false; if (data == null) { // The station is recharging return; } // Preemptively start respawning WorldService.GetInstance().StartRespawn(LocationId); // Init the player's data PlayerService.GetInstance().IncreaseEnergyLevel(data.amountRestored); UIManager.OnShowLoadingView(false); UIManager.OnShowMessageDialog("Energy recharged to 100%!"); }