Note: This is all being done in Unity. I haven't attempted to replicate it in a regular C# console app.
I'm running into an issue that I can't seem to understand. When I apply the System.Serializable
attribute to the below TestingSerializable
class, it seems to force sides = 0
instead of what it should actually be per the below code, sides = 6
.
I know this because when I run the method PrintValue
from within the Manager
class below, the printed value will be zero instead of six. The only way I've found around this is to declare private const int sides = 6
. This will keep it at 6 but I don't completely understand why. I'm assuming it has something to do with the fact that adding the const
access modifier results in the value for 6 being baked into the code.
Mind you, this issue only occurs while running in Editor mode in Unity. When in Game mode it seems to work. This may also be the source of the issue but I'm not entirely sure why. I would like to continue running this in Editor mode, so I would appreciate solutions that allow me to keep operations in the Editor.
Can someone further explain why sides
goes to zero when in a System.Serializable
class unless it has a const
access modifier?
EDIT 1: Added in Manager
class to show how the TestingSerializable
class is being utilized per the comments on this post.
// Manager class to utilize the TestingSerializable class
public class Manager: MonoBehaviour
{
[SerializeField, HideInInspector] private TestingSerializable testingSerializable;
[SerializeField] [Range(2, 256)] private int resolution = 10;
[SerializeField] [Range(1, 10)] private int radius= 5;
private void OnValidate()
{
if (testingSerializable== null)
{
testingSerializable= new TestingSerializable(resolution, radius);
}
testingSerializable.PrintValue();
}
}
[System.Serializable]
public class TestingSerializable
{
private int resolution;
private int radius;
private int sides = 6;
// Constructor
public TestingSerializable(int resolution, int radius)
{
this.resolution = resolution;
this.radius = radius;
}
// Method to print the value `sides`
public void PrintValue()
{
Debug.Log(sides);
}
}