简体   繁体   English

如何在 Unity 中进行网络连接?

[英]How to do networking in Unity?

Hey i am new to developing apps using unity.嘿,我是使用统一开发应用程序的新手。

Needed help with how API calls are made in unity.需要有关如何统一进行 API 调用的帮助。 How Network managers can be made to api calls?如何对 api 呼叫进行网络管理? How objects can be created by mapping JSON?如何通过映射 JSON 来创建对象? Is there a library that is used for doing networking generally?是否有一个通常用于网络的库? Can i get some sample implementation to look at?我可以得到一些示例实现来看看吗?

is this used for networking generally?这通常用于网络吗? https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html?_ga=2.260182286.2011413046.1587971291-955861227.1582882092 https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html?_ga=2.260182286.2011413046.1587971291-955861227.1582882092

Any leads would be of great help.任何线索都会有很大帮助。 Thanks.谢谢。


It's so simple!就是这么简单!

  1. Send a Request with UnityWebRequest (with Post or Get method)使用UnityWebRequest发送请求(使用PostGet方法)
  2. Read the Response value读取响应值
  3. Make a Struct or Class with fields that you have in your response使用响应中的字段创建StructClass
  4. Parse your response to your Json Serialization ( Read Here )解析您对Json Serialization的响应(阅读此处


For example:例如:

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