I’m working with Unity and have encountered an issue related to serialized non-MonoBehaviour classes. Specifically, I have a PlayerController class that derives from MonoBehaviour and contains a public field of type GroundDetection. The GroundDetection class does not derive from MonoBehaviour and is serialized in the Unity Inspector.
Here’s a simplified example:
public class PlayerController : MonoBehaviour
{
public GroundDetection groundDetection;
}
[System.Serializable]
public class GroundDetection
{
public float RayDistance;
public LayerMask GroundLayer;
public GroundDetection(float rayDistance, LayerMask groundLayer)
{
RayDistance = rayDistance;
GroundLayer = groundLayer;
}
}
When I modify the GroundDetection fields in the Inspector and then create a new instance of GroundDetection using new GroundDetection(), all the fields reset to their default values.
For instance:
groundDetection = new GroundDetection(this, groundDetection.RayDistance, groundDetection.GroundLayer);
While initializing fields in the constructor (as shown) works, it’s not an ideal solution for multiple non-MonoBehaviour scripts.
Is there a better way to retain the values of serialized fields in non-MonoBehaviour classes when they are edited from the Unity Inspector?
Any guidance or best practices would be greatly appreciated!
Thank you!
Everything is mentioned above.