Private Fields in Abstract Base Class

Discussion and help for Easy Save 3
Post Reply
Exonto
Posts: 5
Joined: Mon Aug 12, 2019 3:05 am

Private Fields in Abstract Base Class

Post by Exonto »

Hello,

I am running into a pretty odd issue where a private field in an abstract base class is failing to be serialized despite having the [SerializeField] attribute. But when I change the field from private to public or protected, then it gets serialized correctly. This is made even more strange since all the other private fields have no problem being serialized. I have tested saving the same field in another class as private and it worked fine as well (needless to say this took forever to debug). The field in question is a class which contains a couple of generic member variables which are being serialized, in case that matters. My work around for now is to set the field as protected.

Have you run into this issue in the past? It seems very niche. Thank you.

User avatar
Joel
Moodkie Staff
Posts: 2754
Joined: Wed Nov 07, 2012 10:32 pm

Re: Private Fields in Abstract Base Class

Post by Joel »

Hi there,

This is expected behaviour, and is defined by .NET's reflection libraries. Making the field private in the abstract class means that it is no longer in the scope of the derived class, and the abstract class is not treated in the same way as a concrete parent class by reflection, so its fields are not gathered.

As you've suggested, making the abstract field protected or public will bring it back into the scope.

I've added a feature request to add an edge case for this if anyone is interested: https://moodkie.com/forum/viewtopic.php?f=14&t=1717

All the best,
Joel
Joel @ Moodkie Interactive
Twitter - Unity

Exonto
Posts: 5
Joined: Mon Aug 12, 2019 3:05 am

Re: Private Fields in Abstract Base Class

Post by Exonto »

Interesting, okay. It seems this is not a hard and fast rule though since I can serialize private primitives and other classes sometimes. Thank you.

User avatar
Joel
Moodkie Staff
Posts: 2754
Joined: Wed Nov 07, 2012 10:32 pm

Re: Private Fields in Abstract Base Class

Post by Joel »

Hi there,

This is a hard rule set by .NETs reflection classes. Could you give me an example of where you've been able to serialise a private field of an abstract class?

All the best,
Joel
Joel @ Moodkie Interactive
Twitter - Unity

Post Reply