[英]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
.我创建了一个基本的抽象
Character
类(它扩展了MonoBehaviour
),其中包含一些数据,其中之一是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; }
).我不希望更改
maxHealth
,因此我将其设为readonly
并使用属性来更改它( 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.我希望不同的角色具有不同的最大 hp 值,所以我尝试使用构造函数并在那里传递最大健康值,但我无法从统一检查器将值传递给构造函数。
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).有谁知道如何从 Unity 检查器或任何其他方式将值传递给构造函数以实现我想要做的事情(为不同字符制作只读 hp 值并能够仅从统一检查器编辑它们)。
MonoBehaviour instances are created using AddComponent
, not by using new()
. MonoBehaviour 实例是使用
AddComponent
创建的,而不是使用new()
创建的。 Because you are not creating the instance using the new
keyword, there is no constructor to access.因为您没有使用
new
关键字创建实例,所以没有可访问的构造函数。
If you want a variable that can be set from the inspector, but not public, use [SerializeField]
on a private/protected field.如果您想要一个可以从检查器设置但不是公共的变量,请在私有/受保护字段上使用
[SerializeField]
。
[SerializeField]
private float maxHealth;
public float MaxHealth => maxHealth; // Allow others to use this value, but not change it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.