2 回答

TA貢獻1858條經(jīng)驗 獲得超8個贊
由于您的用例實際上是在每次設(shè)置值時執(zhí)行特定行為,因此我建議最好使用Properties。有兩種選擇,具體取決于您的需要一些示例
// Auto property which doesn't have any behavior
// read and write able
public string charName { get; set; }
// read only property
public int currentHP { get; private set; }
// read only property with a backing field
private int _maxHP = 100;
public int maxHP
{
? ? get { return _maxHP; }
}
// same as before but as expression body
private 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 中,您都可以實現(xiàn)其他行為。一旦你這樣做了,你就必須使用支持字段。
例如,您可以像字段一樣使用和訪問它們
someInstance.defense += 40;
執(zhí)行兩者,首先執(zhí)行 getter 以便了解 的當前值_defense,然后添加40并使用 setter 將結(jié)果寫回到_defense。
作為替代方案并且更接近您原來的方法是如上所述的Dictionary。我會把它與適當?shù)慕Y(jié)合起來,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。

TA貢獻1784條經(jīng)驗 獲得超7個贊
如果變量是公共的,您可以直接更改另一個腳本中的變量值。
假設(shè)你有一個玩家對象:
class Player : MonoBehaviour {
public int currentHP;
public int maxHP = 100;
}
您可以從另一個類訪問這些值,如下所示
class Enemy : MonoBehaviour {
public Player player;
void Start() {
player.currentHP -= 10;
}
}
您只需player在 Unity 編輯器中將其拖放到(在本例中)Enemy腳本上即可進行分配。
- 2 回答
- 0 關(guān)注
- 209 瀏覽
添加回答
舉報