1
\$\begingroup\$

I am working on a Unity multiplayer game using mirror, and i separated server- and client-only code using partial classes and preprocessor #if statements based on this answer i found: https://gamedev.stackexchange.com/a/186037/159841

I came across a problem relating to serialized properties and fields with this method. If i switch between client and server define statements, all the inspector values of serialized fields that exist only in the server or client code gets wiped.

Is there any workaround to this? Or should i forget about preprocessor and approach this from a completely different dirrection?

Thanks for any help!

\$\endgroup\$
1
  • \$\begingroup\$ In Unity, the declaration of a serialized field should never be excluded using preprocessors. It may cause serialization errors that happen only on builds (which can be very hard to notice) (e.g. A script behavior (probably SomeBehavior) has a different serialization layout when loading. (Read X bytes but expected Y bytes)). Although the game would run fine, you never know when it could be a problem because it is declared as an "error", not a "warning". \$\endgroup\$ Commented Jan 25, 2022 at 20:16

1 Answer 1

0
\$\begingroup\$

You can add an OR case to your preprocessor directives to always include the field when serializing data in the editor, like so:

#if SERVER_BUILD || UNITY_EDITOR 
    public int someServerOnlyVariableSetInInspector;
#endif

#if !SERVER_BUILD || UNITY_EDITOR
    public int someClientOnlyVariableSetInInspector;
#endif

I'm sorry I neglected that case in my original answer. I've corrected the original post so it shows how to use this pattern to persist serialized data in the editor.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .