Unity WebGL steps on the same pit

1. Get profile information dynamically

Configuration files are generally placed in the streamaassets folder. After packaging, this folder will be in the folder generated by packaging, which is convenient for changing configuration information in the future. In the code, get the location of the folder through Application.streamingAssetsPath.

The configuration file here is of. Ini type. You can read and modify this type of file by directly importing the plug-in: Advanced INI Parser.

Use the source code of this plug-in: (at this time, what's wrong with debugging in VS, but!!!!!!!

   INIParser iniParser = new INIParser();
   iniParser.Open(Application.streamingAssetsPath + "/Config.ini");
   string mUrl = iniParser.ReadValue("ReadDataHttp", "http", "Default value when no value is obtained");

What about my configuration information when packaging webGL to run in the browser? Why didn't you get it? Check posts: WebGL platform reads the configuration file under the StreamingAssets path - Programmer's base camp

It turned out to be the cause of the path. When debugging in VS, it runs on the PC side, and the program can get the files directly under your file path, but it can't be directly obtained by file path when running in the browser. Because it also takes time to obtain the configuration file, the process cannot be directly stuck here, so the co process is used. Modify code on:

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

public class GetConfigFile : MonoBehaviour
{
    public static string url_token = "", url_data = "";
    INIParser iniParser = new INIParser();
    private void Awake()
    {
        StartCoroutine(GetData());
    }

    IEnumerator GetData()
    {
        var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "Config.ini"));
       // Debug.Log("Config.ini address:" + uri.ToString());
        UnityWebRequest www = UnityWebRequest.Get(uri);
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            string value = www.downloadHandler.text;

            iniParser.OpenFromString(value);
            url_token = iniParser.ReadValue("ReadDataHttp", "http_token", "");
            url_data = iniParser.ReadValue("ReadDataHttp", "http_data", "");
           // Debug. Log ("url_token address:" + url_token);
           // Debug. Log ("url_data address:" + url_data);
        }
    }
}

2. About Http requests

At first, I used the class in C # to refer to "using System.Web"; ", the HttpWebRequest class is used to implement the request. Everything is normal when VS is attached to Unity debugging, but an error is directly reported when it is packaged and published to the web side. After outputting the log to the JavaScript Console, it is finally located to HttpWebRequest.GetRequestStream(). However, we don't know what's wrong here. Finally, we find various posts and find that system.web is not supported in webGL( Unity encountered in packaging WebGL!!! [source code attached] insight into ONE_51CTO blog )Crying and hawing

It was originally intended to use the UnitywebRequest provided in Untiy; the usage method refers to this post UnityWebgl platform interacts with JS and uses UnityWebRequest to connect _sunnyblog CSDN blog

According to the operation of this post (Ctrl+C), there is a problem!!!!! Error:

  The location code is here:

  Solution: do not use sendHttpmessage to start the collaboration StartCoroutine(); write it wherever you want to call StartCoroutine();

Modify the code ("add contentType and token to the parameter")

using System;
using System.Text;

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using System.Collections;
using System.IO;
namespace WebApplication
{
    public class RestClient1 : MonoBehaviour
    {
        public RestClient1()
        {
            
        }
        public enum UnityWebRequestType
        {
            POST,
            GET
        }

        /// <summary>
        ///Send HTTP data
        /// </summary>
        ///< param name = "type" > request type < / param >
        ///< param name = "URL" > request address < / param >
        ///< param name = "jsondata" > transmitted data < / param >
        ///< param name = "sendbase64" > whether Base64 encryption is required for sending data < / param >
        ///< param name = "getbase64" > whether Base64 encryption is required to obtain data < / param >
        ///< param name = "failurecallback" > failed callback < / param >
        ///< param name = "successcallback" > successful callback < / param >
        ///< param name = "otherheadername" > additional header name < / param >
        ///< param name = "otherheadervalue" > additional header value < / param >
        ///< param name = "contenttype" > requested contenttype < / param >
        ///< param name = "token" > requested token < / param >
        public IEnumerator WebRequest(UnityWebRequestType type, string url, string jsonData, bool sendBase64, bool getBase64, UnityAction failureCallBack, UnityAction<string> successCallBack, string[] otherHeaderName, string[] otherHeaderValue,string ContentType, string token)
        {
            Debug.Log(type.ToString() + "\t" + url + "\t" + jsonData);
            if (sendBase64)
            {
                jsonData = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonData));
            }
            byte[] body = Encoding.UTF8.GetBytes(jsonData);


            UnityWebRequest unityWeb = new UnityWebRequest(@url, type.ToString());
            unityWeb.uploadHandler = new UploadHandlerRaw(body);
            unityWeb.SetRequestHeader("Content-Type", ContentType);
            if (token != "")
                unityWeb.SetRequestHeader("Authorization", "Bearer " + token);
            if (otherHeaderName != null)
            {
                for (int i = 0; i < otherHeaderName.Length; i++)
                {
                    unityWeb.SetRequestHeader(otherHeaderName[i], otherHeaderValue[i]);
                }
            }

            unityWeb.downloadHandler = new DownloadHandlerBuffer();
            yield return unityWeb.SendWebRequest();

            if (unityWeb.isNetworkError || unityWeb.isHttpError)
            {
                Debug.LogError("UnityWebRequest request was aborted:" + unityWeb.error);
               failureCallBack?.Invoke();
                yield break;
            }

            if (unityWeb.isDone)
            {
                string result = unityWeb.downloadHandler.text;
                if (getBase64)
                {
                    byte[] c = Convert.FromBase64String(result);
                    result = Encoding.UTF8.GetString(c);
                }
                Debug.Log("UnityWebRequest Request succeeded:" + result);
                successCallBack?.Invoke(result);
            }


        }
    }
}

Call:

 (Pseudo code)
using WebApplication;   
void getdata(){
 RestClient1 mClientD1 = new RestClient1(); //Get data
  StartCoroutine(mClientD1.WebRequest(RestClient1.UnityWebRequestType.POST, url, 
body, false, false, failure, succese, name, value, "application/json",token));

}

void failure()//Acquisition failed
{

}

void succese(string value) //Get success, value is the value of the response
{

}

3. On serialization and deserialization of Json

This question annoys me!!!!!!!!!!!!!

unity3d - Unity Json.net System.Reflection.Emit error in iOS - Stack Overflowhttps://stackoverflow.com/questions/41582580/unity-json-net-system-reflection-emit-error-in-ios First of all: I used newtonjason in C # and reported this error in deserialization. I checked it( Unity webgl uses Newtonsoft.Json to serialize the column of _natrace - CSDN blog )Just know to use the package in unit.

Download location:   Releases · SaladLab/Json.Net.Unity3D · GitHub

Usage: g

///Namespace
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

//
  SendData mSenData;
  ...
  string Str= JsonConvert.SerializeObject(mSendData);
  class SendData
    {
        public List<QueryDbData> queries;
        public string table;
        public string type;
    }

  string Str= JsonConvert.SerializeObject(object obj);

//
  JObject obj = JsonConvert.DeserializeObject<JObject>(string str)

Tags: Unity webgl

Posted on Tue, 23 Nov 2021 02:07:38 -0500 by DJTim666