Make all Elements of Array a Certain Percentage

I have an array that is spawn chances, so I would like all the numbers of said array to be editable in the inspector, but is there an attribute or something that would guarantee all numbers add up to 100?

So, say there’s 3 values, 25,25, and 50. you want to add to one of the 25s and make it idk, 40. Is there a way to make it average out the values on start, so it doesn’t just have 25,40,and 50, but it automatically averages them out so they all add to 100? Because obviously I don’t want to have the total add up to 115 lol. I know there’s gotta be a math equation for this, but I forget high school lol.

This is partly for the convenience of the person I’m working with, so he can adjust the spawn percentages freely, without the spawn system just getting completely broken

Thanks!

Edit: Okay, well I’m 95% sure this worked,

 int GetFishToSpawn()
    {
        float num = Random.Range(0f, 1f);
        float total = 0;
        float numberForAdding = 0;
       
        for (int i = 0; i < spawnChances.Length; i++)
        {
            total += spawnChances[i];
        }

        for (int i = 0; i < spawnChances.Length; i++)
        {
            if((spawnChances[i]/total) + numberForAdding >= num)
            {
                return i;
            }
            else
            {
                numberForAdding += spawnChances[i] / total;
            }
        }

        return 0;
    }

Basically what it does is generates a number from 0-1, and compares the numbers to the sum of all numbers in the list to get the percentage. Pretty sure this works with any numbers, so you can set one object to 999999 and it will almost always spawn. lol

You can do that, but it’s probably not necessary. The more typical solution is to change your random selection algorithm so that instead of picking out of 100, it picks out of whatever the total happens to be.

1 Like