Hello, i need a help
I’m trying to make a code to on click in a button, the game distribute the player stats, with a minimal value of 2 and maximum 6, and the sum need to be 16.
Your loop is doing something wrong. The idea is right - distribute stats randomly until the sum is exactly 16. What you need to do is to have a while-loop running until the sum is exactly 16, adding to one random stat each time you go through the loop:
void randomStats() {
atk = 2;
def = 2;
dex = 2;
intel = 2; //stay consistent - either use 'attack' and 'intelligence', or 'atk' and 'intel'
while (atk + def + dex + intel < 16) {
int choice = Random.Range(0, 4); //Will give random between 0 and 3!
switch (choice) {
case 0:
if (atk < 6)
atk++;
break;
case 1:
if (def < 6)
def++;
break;
case 2:
if (dex < 6)
dex++;
break;
default:
if (intel < 6)
intel++;
break;
}
}
}
It would possibly be even easier to use an array, and have each index be a different stat:
public void randomStats() {
int[] stats = {2, 2, 2, 2};
while (Sum(stats) < 16) {
int randomIndex = Random.Range(0, 4);
if (stats[randomIndex] < 6)
stats[randomIndex]++;
}
atk = stats[0];
def = stats[1];
dex = stats[2];
intel = stats[3];
}
private int Sum(int[] stats) {
int sum = 0;
for (int i = 0; i < stats.Length; i++) {
sum += stats*;*
} return sum; } I think the second one is prettier, but it’s up to you which one you like the best. Hope this helps!