Home > Mobile >  How can i serialize property of c# in Unity
How can i serialize property of c# in Unity

Time:12-15

I think it's inefficient to implement these two lines of variables.

[SerializeField] private int i;
public int I => i;

So I would like to express this in one line, but this is not serialized in Unity.

[SerializeField] public int I { get; private set; }

I want to make it visible in Unity Inspector.

So my question is below.

  1. Can this property be serialized?
  2. If impossible, is it possible to solve it in a way other than the above?

CodePudding user response:

Starting in C# 7.3 (which Unity supports), you can now add attributes to the backing fields generated by autoproperties.

For this instance, where the backing field is auto generated, you can add this attribute:

[field: SerializeField] public int MyField { get; private set; }

This serializes the backing field as if it were a normal variable.

CodePudding user response:

Well that's correct behavior.

[SerializeField] 
public int I { get; private set; }

This is a property (with a getter and setter accessor), not a variable. These are not, cannot and should not be serialized. If you want an exposed variable that you can set (or see) in the Inspector, use a public modifier on a variable, not a function or accessor. If you don't want the variable to be public, then it can be protected or private, but marked with [SerializeField] as you already know. This is by design and is the correct approach.

Some additional information as it seems you might have different expectations on how Unity should behave:

Unity has some different paradigms as opposed to conventional programming and this is by design as the engine has a different approach to how each game object (and by this I mean any UnityEngine.Object descendant, not just UnityEngine.GameObject) interacts with another and how it should be implemented in the game (i.e. adding it as a Component or ScriptableObject as opposed to using new() or how the garbage collection of said objects is handled in the engine). This means that if you want the convenience of the Inspector real-time editing features, you'll need to "break" some rules regarding object access and mark a lot of variables as public. If you don't want that, there's always the option of referencing them in code or using ScriptableObjects, but that might be overkill in some cases.

Unity is also akin to encapsulated, as extending existing deployments is done differently from C#, so using public or private variables or functions doesn't change much. It's not like somebody is going to make a library and extend from your game's library since Unity doesn't work that way.

  • Related