I tried to read up why mutable structs are evil, which was previously posted here.
Why are mutable structs “evil”?
But my post is more about a specific scenario.
Given following scenario
I want to have a small, fast to serialize "data class", to speed up my Save/Load Mechanism
I have a Player class which I can use inside the Unity Editor. This Player class has a member variable called "Stats" which is a struct.
public class Player : MonoBehaviour
{
public PlayerStats Stats;
}
Below you can see the System.Serializable struct I am using as "data class"
[System.Serializable]
public struct PlayerStats
{
public uint Speed;
public void SetSpeed(uint speed)
{
this.Speed = Math.clamp(speed, Rules.MinSpeed, Rules.MaxSpeed);
}
}
So later on to prevent the overhead i am experiencing from serializing a MonoBehaviour i use
JsonUtility.ToJson(player.Stats)
Now my question is, if I use SetSpeed anywhere in the code to modify the Value inside the struct
player.Stats.SetSpeed(3);
does this now lead to copies of the struct being made, because the value is being modified?
Any clarifications would be great.