[SerializeField] Field is never assigned to, and will always have its default value 0

The warning “Field is never assigned to, and will always have its default value 0” appears whenever using [SerializeField] on a variable.

Is there any other solution to this other than disabling the error message and using public instead?

Yes, I know this has been addressed before, but are there any new solutions?

WarmedxMints is right. From a pure OOP point of view nobody is able to actually change the value of the variable since it’s private. Most serialization systems actually bypass the protection level of variables in order to read / write the values through reflection. This has nothing to do with adding the SerializeField attribute. That attribute is just a custom attribute that comes with Unity. The compiler has no idea what this is good for. Attributes actually don’t do anything as they are just metadata. It’s always some code of a subsystem which actually reads and interprets attributes.

The compiler warning is just a warning, not an error. You can not “tell” the compiler that this field is initialized through reflection. You can tell it to ignore the warning (which is not a great solution). The best fix is to simply initialize the variable yourself. It can be initialized with 0 / null.

For anyone using Rider or other editors/linters with warnings about redundant initializations, I’ll post the stategy I’ve been using.

As per this SO question about general C# warning suppression, you can wrap your private serialized fields in #pragma preprocessor statements to disable the compilers check for CS0649.

#pragma warning disable 0649
	[SerializeField] private string group;
	[SerializeField] private string kind;
	[SerializeField] private int order;
	[SerializeField] private int precedence;
#pragma warning restore 0649

On the downside, it adds more verbosity to the code, but it also makes sure to limit the scope to just your reflection populated fields. It also plays nice with most linters and makes it clear to other (probably new to Unity) devs that there’s some non-standard stuff going on here.

And if you don’t mind including the whole file in the scope, you can just leave out the restore directive. Though, in my case I naturally group my private serialized fields together anyways, so it’s clean enough and I only have to do it once per file.

Guys, listen to Bunny83. Don’t obfuscate nor complicate this. Just initialize fields to something, anything, null, zero or default(T); case closed.

The approach I use for this situation which works better for me than turning off the warnings is to change private to protected. This way the other classes are still unable to change that field - which is the main reason I decided to use [SerializeField] private instead of public fields in the first place. The only downside for this solution is that the derived classes will have access to this field but I really doubt this would be an issue in a game.