简体   繁体   English

如何从统一检查器将值传递给构造函数

[英]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.

相关问题 Unity 5:如何在检查器的按钮单击功能上传递多个参数? - Unity 5: How to pass multiple parameters on button click function from inspector? 统一错误(脚本检查器3):不允许从ScriptableObject构造函数调用GetBool - Error in unity(Script Inspector 3): GetBool is not allowed to be called from a ScriptableObject constructor 检查器值无法从Unity3d中的另一个类访问 - Inspector value cannot access from another class in Unity3d 在Unity中,如何在Inspector中更改布尔值时触发Set方法? - In Unity, How to Trigger the Set Method When Changing Boolean Value in the Inspector? 在Unity配置中,如何将connectionString传递给构造函数? - In Unity config, how to pass connectionString to a constructor? 如何从代码(Unity)在检查器中打开资产的孩子 - How to open a child of asset in inspector from code (Unity) 如何在Unity Inspector中隐藏组件 - How to hide components in Unity Inspector 如何使用 ConfigurationManager 将 Unity3d 中的连接字符串值传递到类库 - How to pass connectionstring value from Unity3d to a classlibrary with ConfigurationManager Inspector中分配的Unity值在代码中抛出空 - Unity Value Assigned in Inspector Throws Null in Code 如何从统一向ios传递统一窗口 - How to pass unity window to ios from unity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM