Home > Blockchain >  How to validate multiple inputs in in Unity. Inputs are in a list of CUSTOM CLASS
How to validate multiple inputs in in Unity. Inputs are in a list of CUSTOM CLASS

Time:11-04

In Mount Blade: Warband Quick Battle Mode, The user is allowed to choose the army composition as shown in the picture:

Mount Blade Warband Quick Battle Screen

As the user slides one of the sliders, the other ones automatically move to a reasonable value.

I want to do something similar But In the Unity Inspector. I have a class that contains a GameObject and a byte slider (Using Range Attribute):
My Inspector

How can I achieve similar results, for the spawn chance of every grid item?

Spawn Chance is a byte .

I used the OnValidate function. I obtained the spawn chances as follows :

// 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
        }
    }
}

CodePudding user response:

You are expecting values between 0 and 1, which you multiply with 100 here:

item.spawnChance = (byte)(item.spawnChance / sum * 100);

but it snaps to 0 or 100. That's because item.spawnChance / sum will be 0 or 1.

spawnChance is a byte (whole number like int) and dividing that will not result in a fraction like 0.34. You need a float for this operation.

Simple fix, cast the spawnChance to float before dividing by sum:

item.spawnChance = (byte)((float)item.spawnChance / sum * 100);
  • Related