• Hello
Search Results for

    Show / Hide Table of Contents

    JSON with Unity JsonUtility

    Unity's JsonUtility can save and load protected primitives. You do not add a converter.

    JsonUtility only writes fields. Put the protected value on a class marked [Serializable]. A property is left out of the file.

    using System;
    using GUPS.AntiCheat.Protected;
    using UnityEngine;
    
    [Serializable]
    public class SaveGame
    {
        public ProtectedBool hasKey;
        public ProtectedInt32 coins;
        public ProtectedVector3 position;
    }
    
    string json = JsonUtility.ToJson(save);
    SaveGame loaded = JsonUtility.FromJson<SaveGame>(json);
    

    The file looks like this:

    {"hasKey":{"fakeValue":true},"coins":{"fakeValue":10},"position":{"fakeValue":{"x":1.0,"y":2.0,"z":3.0}}}
    

    Each protected value is an object with one field, fakeValue. That field holds the real value. A vector or a quaternion keeps Unity's usual x, y, z, and w inside fakeValue.

    Unity writes the fakeValue object shown above. A file shaped like {"hasKey":true} does not load into a protected field.

    Note

    A date is written as a large whole number, not as text such as 2020-01-01. A decimal is written as a floating-point number, so a very long decimal can change a little.

    Keep this file separate from a save made with Newtonsoft.Json or System.Text.Json. Those libraries write a normal JSON value, with no fakeValue wrapper.


    Back to the FAQ.

    In This Article
    Back to top GuardingPearSoftware documentation