- Home /
Distribute a total value from a variable to multiple other variables?
Sorry if the question is a bit unclear, but to put it into perspective I will share my idea how I want this to work. I've searched through the forum but can't really find anything that answers my question.
I'm working on a loot system for a (hopefully) upcoming RPG-like game. I'm still a beginner to both Unity and C# but I feel I'm getting the hang on it pretty well.
The idea with the loot is: Each item-types (Sword, Crossbow, Armor etc) will roll a random "gearscore" (haven't come up with a proper name yet). The idea with the gearscore is that the value of the gearscore is the total value of points to distribute to the items stats.
Example:
Itemtype: Sword
Gearscore: 150
150 points will be randomly distributed to Strength, Attack speed, damage, etc etc).
Example:
150 points (the Gearscore) will be distributed like this (by random):
Strength: 55 p
Attack Speed: 25 p
Damage: 50 p
Critical Chance: 20 p
What would be the most effective, and easiest way to implement this function, to distribute the Gearscore to my stats (multiple variables)? How would you do it?
I don't need a working code for it, just some ideas thrown at me from people that have been doing this for a while :)
Answer by s_awali · Dec 05, 2018 at 08:03 PM
Let's take for example a piece of equipment with 3 attributes and 150 points to distribute.
If you want a very simple code to use, I would go like this:
int numberOfPointsToDistribute = 150;
int numberOfAttributes = 3;
int pointsLeft = numberOfPointsToDistribute;
for(int i = 0; i < numberOfAttributes; i++)
{
int randomPoints = Random.Range(0, pointsLeft);
attributes[i] = randomPoints;
pointsLeft -= randomPoints;
}
One flaw of this script is that the distribution is not evenly made for each attributes: the very first one have higher chance of having the maximum number (since random would pick from [0] to [150]) than the last one (since random would pick from [0 + attribute_1 + attribute_2 + ... + attribute_n-1] to [150]).
If you want a more even way of doing it, I would go like that:
Get the average value for each attributes (in our case, 150 / 3 = 50)
For each attribute, give X points, where X = Mathf.Clamp(0, 150, average + Random.Range(-average, average))
Your answer
![](https://koobas.hobune.stream/wayback/20220612183415im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
One of my variable won't increase. [Answered.] 1 Answer
Item/inventory system-equipable items 1 Answer
RPG for teaching ESL (English as a second language) 2 Answers
Change a variable via functions 1 Answer
RPG Tutorial in Javascript 1 Answer