简体   繁体   中英

How to pass value to constructor from unity inspector

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM