FANDOM


This is an example script to show one way of transferring Actions to and from strings using Json.

To use it, create a C# script named JsonExample, and paste the code below into it. Then place the component "Json Example" in your scene, and assign an ActionList from the scene into its Inspector field. You can then use the component's context menu (the cog icon to the top-right) to copy that ActionList's action data to and from Json. When stored, the Action data will appear beneath in the Inspector.

JsonExample.cs:

	using UnityEngine;
using System.Collections.Generic;
using AC;

public class JsonTest : MonoBehaviour
{

[SerializeField] private ActionList actionList;
[SerializeField] private JsonAction[] jsonActions;


[ContextMenu ("ToJson")]
private void ToJson ()
{
int length = actionList.actions.Count;
jsonActions = new JsonAction[length];

for (int i=0; i<length; i++)
{
string jsonAction = JsonUtility.ToJson (actionList.actions[i]);
string className = actionList.actions[i].GetType ().ToString ();

jsonActions[i] = new JsonAction (className, jsonAction);
}
}


[ContextMenu ("FromJson")]
private void FromJson ()
{
List<Action> newActions = new List<Action>();
for (int i=0; i<jsonActions.Length; i++)
{
newActions.Add (jsonActions[i].CreateAction ());
}

actionList.actions = newActions;
}


[System.Serializable]
private struct JsonAction
{

[SerializeField] private string className;
[SerializeField] private string jsonData;


public JsonAction (string _className, string _jsonData)
{
if (_className.StartsWith ("AC."))
{
_className = _className.Substring (3);
}

className = _className;
jsonData = _jsonData;
}


public Action CreateAction ()
{
Action newAction = (Action) ScriptableObject.CreateInstance (className);
JsonUtility.FromJsonOverwrite (jsonData, newAction);
return newAction;
}

}

}
Community content is available under CC-BY-SA unless otherwise noted.