Unity publishes a method reference for processing arrays with JsonUtility for WebGL communication

JsonUtility cannot parse the json array, nor can it correctly convert the array to json. Before, each array was converted into an object, but it was inconvenient to use the front end. After searching and querying, I felt that this solution was reliable.

The first is to create a generic class:

[Serializable]
public class Wrapper<T>
{
	public T[] items;
}

When Unity needs to pass an array as a parameter to the page, it actually wraps the array into a Wrapper object first,

void OnSetFixedNodeList(TranNode[] tranNodes)
{
	if (Application.platform != RuntimePlatform.WebGLPlayer) return;
	//
	if (tranNodes == null || tranNodes.Length == 0) return;

	string[] names = new string[tranNodes.Length];
	for (int i = 0; i < names.Length; i++)
	{
		names[i] = tranNodes[i].name;
	}

	Wrapper<string> wrapper = new Wrapper<string>();
	wrapper.items = names;

	WebUpdateFixedNodeList(JsonUtility.ToJson(wrapper));
}

What is obtained on the page is a json object wrapped with an array, and the page parses the json object to obtain an array, similar to the following:

var fixedNodeList;
function UpdateFixedNodeList(nodeList)
{
	var obj = JSON.parse(nodeList);		fixedNodeList = obj.items;
	console.log(fixedNodeList);
}

When the page needs to send a message to unity, it should first wrap the array into a json object, wrapping an array named param like this:

function SendMsgWithJsonArray(funName, param)
{
    if(myGameInstance != null)
    {
        myGameInstance.SendMessage('_InternalObj', funName, JSON.stringify({"items":param}));
    }
}

When Unity receives such a pick-up object, it first converts the json into an object, and then extracts the array, similar to this:

static public void JsonArray<T>(string json, UnityAction<T[]> act)
{
	Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
	if (wrapper != null)
	{
		act?.Invoke(wrapper.items);
	}
	else
	{
		string tName = wrapper.GetType().Name;
		Debug.Log("U3DLog:ParseExecute.JsonArray<" + tName + "> failed,because can NOT parse " + json + ".");
	}
}

Supongo que te gusta

Origin blog.csdn.net/ttod/article/details/130922589
Recomendado
Clasificación