I have a base abstract Character
class I created (it extends MonoBehaviour
) which contains some data, one of which is maxHealth
. I don't want the maxHealth
to be changed and so I made it readonly
and use a property to change it (public float MaxHealth { get; }
).
I want different characters to have different max hp values so I tried to use a constructor and pass in the max health there but I can't pass a value to the constructor from the unity inspector.
Does anyone have any idea how to pass a value to a constructor from the Unity inspector or any other way to achieve what I'm trying to do (make readonly hp values for different characters and to be able to edit them from just the unity inspector).
CodePudding user response:
MonoBehaviour instances are created using AddComponent
, not by using new()
. Because you are not creating the instance using the new
keyword, there is no constructor to access.
If you want a variable that can be set from the inspector, but not public, use [SerializeField]
on a private/protected field.
[SerializeField]
private float maxHealth;
public float MaxHealth => maxHealth; // Allow others to use this value, but not change it