Assigning variables depending on other variables
I know the title is a little vague but I couldn't think of anything better, sorry!
I'll try to explain: Let's say I pick 1 "Unit" out of a maximum of 6, and I want to change it's "Strength" variable, which is kept in another script which keeps track of every 6 units "Strength" (as "unit1strength, unit2strength", for example).
The units are part of a List of units, going from 0 to 5 (6 total). What I want to do is assign it's "Strength" as following:
if(unit == unitsList[4])
{
unit.GetComponent<Unit>().strength = anotherscript.unit5strength;
}
if(unit == unitsList[5])
{
unit.GetComponent<Unit>().strength = anotherscript.unit6strength;
}
However, I feel like the code becomes really redundant and there's a better way to put it without copypasting the whole thing and changing just the numbers, but I'm relatively new at coding and can't figure out how. If I did it the way I showed above, there would be an enormous chunk of unnecessary code, since in the game, "Strength" is only one of the many attributes the "Unit" has.
I know I can use "Switch" as well, but it doesn't change the situation.
Thanks in advance and a good day to everyone!!
Answer by landon912 · Sep 30, 2015 at 12:43 AM
You can modify some of the code to something like this:
for(int i = 0; i < unitList.Count; i++)
{
unitList[i].GetComponent<Unit>.strength = anotherScript.unitStrengthValues[i];
}
Here if you store the unit's strength values in an array, you can simply index them together. I also question why they're separate to begin with, but I digress. I hope this helps.
Your answer
![](https://koobas.hobune.stream/wayback/20220612035510im_/https://answers.unity.com/themes/thub/images/avi.jpg)