修改另一个脚本中的变量

我目前正在为 Unity 创建一个包含许多变量的 C# 脚本,并且我希望这些变量可以从其他脚本中更改。


为此,我目前编写了一个函数,该函数询问变量的名称(作为字符串),然后对每个变量使用 switchcase。


public string charName;


public int currentHP;

public int maxHP = 100;


public int strength;

public int defense;


public void ChangeValue(string valueToChange, int howMuch)

{

    switch (valueToChange)

    {

        case "currentHP":

            currentHP += howMuch;

            break;


        case "maxHP":

            maxHP += howMuch;

            break;


        case "strength":

            strength += howMuch;

            break;


        case "defense":

            defense += howMuch;

            break;

    }

}

有更有效的方法吗?switch case 看起来效率很低,每次我想向脚本添加新变量时都需要修改它。


对我来说最完美的事情是询问变量作为参数,但我无法找到一种方法来做到这一点。


感谢您的时间 !


犯罪嫌疑人X
浏览 71回答 2
2回答

猛跑小猪

由于您的用例实际上是在每次设置值时执行特定行为,因此我建议最好使用Properties。有两种选择,具体取决于您的需要一些示例// Auto property which doesn't have any behavior// read and write ablepublic string charName { get; set; }// read only propertypublic int currentHP { get; private set; }// read only property with a backing fieldprivate int _maxHP = 100;public int maxHP{    get { return _maxHP; }}// same as before but as expression bodyprivate int _strength;public int strength { get => _strength; }// finally a property with additional behaviour // e.g. for the setter make sure the value is never negative private int _defense;public int defense{    get { return _defense; }    set { _defense = Mathf.Max(0, value); }}正如您所看到的,属性在某种程度上取代了 getter 和 setter 方法,在某些情况下甚至充当字段的角色(自动属性)。在 getter 和 setter 中,您都可以实现其他行为。一旦你这样做了,你就必须使用支持字段。例如,您可以像字段一样使用和访问它们someInstance.defense += 40;执行两者,首先执行 getter 以便了解 的当前值_defense,然后添加40并使用 setter 将结果写回到_defense。作为替代方案并且更接近您原来的方法是如上所述的Dictionary。我会把它与适当的结合起来,enum例如public enum ValueType{    MaxHP,    Strength,    Defense,    CurrentHP}private Dictionary<ValueType, int> Values = new Dictionary<Value, int>{    {ValueType.MaxHP, 100},    {ValueType.Strength, 0 },    {ValueType.Defense, 0 },    {ValueType.CurrentHP, 0 }};public void ChangeValue(ValueType valueType, int value){    Values[valueType] += value;    // do additional stuff}将该方法要控制的值添加到enum和 的开销最小Dictionary。

噜噜哒

如果变量是公共的,您可以直接更改另一个脚本中的变量值。假设你有一个玩家对象:class Player : MonoBehaviour {&nbsp; &nbsp; public int currentHP;&nbsp; &nbsp; public int maxHP = 100;}您可以从另一个类访问这些值,如下所示class Enemy : MonoBehaviour {&nbsp; &nbsp; public Player player;&nbsp; &nbsp; void Start() {&nbsp; &nbsp; &nbsp; &nbsp; player.currentHP -= 10;&nbsp; &nbsp; }}您只需player在 Unity 编辑器中将其拖放到(在本例中)Enemy脚本上即可进行分配。
打开App,查看更多内容
随时随地看视频慕课网APP