How to save JsonAsset from editor script

Hi, I have a problem.
I want to edit my JsonAsset in custom editor window. However, when I’am trying to save changes and calling JsonAsset.Save(), it returns false, and my changes do not apply.

The class for JsonAsset looks like this:

[Serializable]
public class GraphData
{
    [ShowInEditor]
    [Serialize] private List<GraphNodeData> _nodeData = new List<GraphNodeData>();

    [NoSerialize] private Dictionary<Guid, GraphNode> _graph;

    [NoSerialize] public Dictionary<Guid, GraphNode> Graph => _graph ?? (_graph = CreateDictionary());

    private Dictionary<Guid, GraphNode> CreateDictionary()
    {
        \\ ... Create Dictionary from _nodeData
    }

    public void SaveGraph()
     { 
        \\ ... Update _nodeData, using Graph dictionaty
     }

    [Serializable]
    private class GraphNodeData
    {
        public Guid Id;
        public Float3 Position;
        public List<Guid> Neighbours = new List<Guid>();
    }
}

Custom editor window code:

public class GraphBuildEditorWindow : CustomEditorWindow
    {
        private AssetPicker _assetPicker;

        public override void Initialize(LayoutElementsContainer layout)
        {
            layout.Label("Grath Data", TextAlignment.Center);
            layout.Space(20);

            _assetPicker = layout.Custom<AssetPicker>("Grath data").CustomControl;

            var button = layout.Button("Generate grath", Color.Blue);

            button.Button.Clicked += GenerateGraph;
        }

        private void GenerateGraph()
        {
            var asset = _assetPicker.SelectedAsset;

            if (!asset || !(asset is JsonAsset json) || !(json.Instance is GraphData graphData))
            {
                MessageBox.Show("You should assign appropriate GraphData asset.");
                return;
            }

            \\  ... Graph Generation ...

            graphData.SaveGraph();
            json.Save();
        }

Nethermind, I found a workaround, just used
Editor.SaveJsonAsset(json.Path, graphData);
instead of json.Save();

1 Like