Created
February 8, 2021 11:48
-
-
Save Matthew-J-Spencer/8da232ef3d3ce81a0f4a2cb087eb740b to your computer and use it in GitHub Desktop.
NetworkManager example from https://youtu.be/K9uVHI645Pk
This file contains hidden or 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 NetworkManager : MonoBehaviour { | |
private void Start() { | |
StartCoroutine(MakeRequests()); | |
} | |
private IEnumerator MakeRequests() { | |
// GET | |
var getRequest = CreateRequest("https://jsonplaceholder.typicode.com/todos/1"); | |
yield return getRequest.SendWebRequest(); | |
var deserializedGetData = JsonUtility.FromJson<Todo>(getRequest.downloadHandler.text); | |
// POST | |
var dataToPost = new PostData(){Hero = "John Wick", PowerLevel = 9001}; | |
var postRequest = CreateRequest("https://reqbin.com/echo/post/json", RequestType.POST, dataToPost); | |
yield return postRequest.SendWebRequest(); | |
var deserializedPostData = JsonUtility.FromJson<PostResult>(postRequest.downloadHandler.text); | |
// Trigger continuation of game flow | |
} | |
private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null) { | |
var request = new UnityWebRequest(path, type.ToString()); | |
if (data != null) { | |
var bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data)); | |
request.uploadHandler = new UploadHandlerRaw(bodyRaw); | |
} | |
request.downloadHandler = new DownloadHandlerBuffer(); | |
request.SetRequestHeader("Content-Type", "application/json"); | |
return request; | |
} | |
private void AttachHeader(UnityWebRequest request,string key,string value) | |
{ | |
request.SetRequestHeader(key, value); | |
} | |
} | |
public enum RequestType { | |
GET = 0, | |
POST = 1, | |
PUT = 2 | |
} | |
public class Todo { | |
// Ensure no getters / setters | |
// Typecase has to match exactly | |
public int userId; | |
public int id; | |
public string title; | |
public bool completed; | |
} | |
[Serializable] | |
public class PostData { | |
public string Hero; | |
public int PowerLevel; | |
} | |
public class PostResult | |
{ | |
public string success { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
works well.