When I create this class and open a List with this custom class, the one with FullName can be seen in the inspector, but the one with Age cant be. I wonder why? Since the Age is public property, it should be seen as it is public get and set.
[Serializable]
public class YoungPerson
{
public string FullName;
public string fullname
{
get { return FullName;}
set { FullName = value; }
}
public int Age { get; set; }
public YoungPerson(string fullName, int age)
{
this.FullName = fullName;
this.Age = age;
}
}
CodePudding user response:
Because what you see in the Inspector is not the property
public string fullname { ... }
but rather the serialized field
public string FullName;
You can already see that on the naming - fullname
would be displayed as Fullname
not as Full Name
as per ObjectNames.NicifyVariableName
;)
Unity's Serializer doesn't serialize properties by default - see Script Serialization -> Serialization of properties
.
You can either add a backing field implementation like you also did for the name e.g.
// In that case I would always rather go for private
// anything else is just confusing / why would you use the property
// when you can anyway read/write the field directly
[SerializeField] private int age;
public int Age
{
get => age;
set => age = value;
}
or - as already mentioned by this answer - force serialize the property via (unfortunately undocumented for whatever reason)
[field: SerializeField]
public int Age { get; set; }
as also mentioned by the other answer this has some hickups (see e.g. this thread) though
CodePudding user response:
Unity Editor dont show property in Inspector, you see on public string FullName
field but not public string fullName
property. Make public field for Age to see this in inspector
CodePudding user response:
Unity can't serialize properties, it's mentioned in the docs.
CodePudding user response:
As others have mentioned, Unity does not officially support serializing properties. But it is possible.
This should work just fine:
[field: SerializeField] public string FullName { get; set; }
However, it still has some quirks, as mentioned here. You'll have to judge for yourself whether it's a good idea to use it.