簡體   English   中英

如何在 Unity 中進行網絡連接?

[英]How to do networking in Unity?

嘿,我是使用統一開發應用程序的新手。

需要有關如何統一進行 API 調用的幫助。 如何對 api 呼叫進行網絡管理? 如何通過映射 JSON 來創建對象? 是否有一個通常用於網絡的庫? 我可以得到一些示例實現來看看嗎?

這通常用於網絡嗎? https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html?_ga=2.260182286.2011413046.1587971291-955861227.1582882092

任何線索都會有很大幫助。 謝謝。


就是這么簡單!

  1. 使用UnityWebRequest發送請求(使用PostGet方法)
  2. 讀取響應值
  3. 使用響應中的字段創建StructClass
  4. 解析您對Json Serialization的響應(閱讀此處


例如:

using System;
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

// UnityWebRequest.Get example

// Access a website and use UnityWebRequest.Get to download a page.
// Also try to download a non-existing page. Display the error.

public class Example : MonoBehaviour
{
    [Serializable]
    public class MyClass
    {
        public int level;
        public float timeElapsed;
        public string playerName;
    }

    void Start()
    {
        // A correct website page.
        StartCoroutine(GetRequest("https://www.example.com"));

        // A non-existing page.
        StartCoroutine(GetRequest("https://error.html"));
    }

    IEnumerator GetRequest(string uri)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            string[] pages = uri.Split('/');
            int page = pages.Length - 1;

            if (webRequest.isNetworkError)
            {
                Debug.Log(pages[page] + ": Error: " + webRequest.error);
            }
            else
            {
                var json = webRequest.downloadHandler.text;
                Debug.Log(pages[page] + ":\nReceived: " + json);

                var myObject = JsonUtility.FromJson<MyClass>(json); //<-- This is your result object
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM