在刀鋒山:戰團快速戰斗模式中,用戶可以選擇軍隊組成,如圖所示:

當用戶滑動其中一個滑塊時,其他滑塊會自動移動到一個合理的值。
我想做類似的事情,但在 Unity Inspector 中。我有一個包含 GameObject 和位元組滑塊的類(使用范圍屬性):

對于每個網格專案的生成機會,我怎樣才能獲得類似的結果?
生成機會是一個
byte。
我使用了這個OnValidate功能。我獲得的產卵機會如下:
// the sum of all spawn chances should be 100
List<byte> spawnChances = new List<byte>();
foreach (Spawnable item in gridItems) {
spawnChances.Add(item.spawnChance);
}
if (spawnChances.Count > 0) {
byte sum = 0;
foreach (byte chance in spawnChances) {
sum = chance;
}
if (sum != 100) {
foreach (Spawnable item in gridItems) {
item.spawnChance = (byte)(item.spawnChance / sum * 100);
// if i do this, when i change the value
// the editor snaps it to 100
}
}
}
uj5u.com熱心網友回復:
您期望的值介于 0 和 1 之間,在此處乘以 100:
item.spawnChance = (byte)(item.spawnChance / sum * 100);
但它會捕捉到 0 或 100。那是因為item.spawnChance / sum將是 0 或 1。
spawnChance 是一個位元組(整數,如 int),除法不會產生像 0.34 這樣的小數。此操作需要一個浮點數。
簡單的修復,在除以總和之前將 spawnChance 轉換為浮動:
item.spawnChance = (byte)((float)item.spawnChance / sum * 100);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/526720.html
