Encapsulating member variables of a raw C# class that was marked as serializable

37 views Asked by At

I have a raw C# class that is marked as [Serializable]. The fields are all public since the object is being saved to a file with Newtonsoft JSON.NET.

[Serializable]
public class PlayerGlobalAggregateData
{
    public int timesPlayed;
    public int timesCleared;
    public int timesFailed;

    public PlayerGlobalAggregateData(int timesPlayed = default,
                                     int timesCleared = default,
                                     int timesFailed = default)
    {
        this.timesPlayed = timesPlayed;
        this.timesCleared = timesCleared;
        this.timesFailed = timesFailed;
    }
}

Now I have a scriptable object in which I have this class instance as a member variable:

public class PlayerGlobalAggregateModel : ScriptableObject
{
    private PlayerGlobalAggregateData _data;

    public void SetModelData(PlayerGlobalAggregateData data)
    {
        _data = data;
        //TestCoroutine();
    }

    public PlayerGlobalAggregateData GetPlayerAggregateData()
    {
        //TestCoroutine();
        return _data;
    }
}

The idea behind doing things like this is that I load all the data from the file into the member variable _data using the method SetModelData(); method. And throughout the game, I modify the model and when saving back to the file I use GetPlayerAggregateData().

Now the thing that is troubling me is that any class that has this scriptable object as a reference can access all the data in the _data field and even modify it since the fields are all public in the PlayerGlobalAggregateData class.

How can I encapsulate those fields better?

I am not able to figure out how to go about this.

1

There are 1 answers

0
hijinxbassist On

You can mark the fields as private and decorate with appropriate attributes, eg.

[SerializeField][JsonProperty] private int someDataField; 

Then expose a getter property for each variable that should be accessible externally, eg.

public int SomeDataField => someDataField;  

SerializeFieldAttribute
This allows the private field to be serialized and editted in the unity inspector

[SerializeField]

JsonPropertyAttribute
This allows JSON.Net to serialize the private field

[JsonProperty]