- Home /
variables within variables?
I have been writing some code, but it takes me a lot of time to write every single variable. I was hoping I could make it more efficient by using variables withing variables. Or at least, string or ints within variables to designate the variables that I want to alocate the value of.
So, for example, I have:
if (Input.GetKeyDown (KeyCode.Alpha2)) {
key2 = false;
obj2Type = 0;
obj2CurAmmo = 0;
obj2MaxAmmo = 0;
obj2NextFire = 0;
this.GetComponent<UiCoordination> ().DestroyAbilityImage (2);
}
if (Input.GetKeyDown (KeyCode.Alpha3)) {
key3 = false;
obj3Type = 0;
obj3CurAmmo = 0;
obj3MaxAmmo = 0;
obj3NextFire = 0;
this.GetComponent<UiCoordination> ().DestroyAbilityImage (3);
}
And I was hoping I could write something of the sort:
if (Input.GetKeyDown (KeyCode.Alpha2)) {
AssignVariable(2);
}
if (Input.GetKeyDown (KeyCode.Alpha3)) {
AssignVariable(3);
}
AssignVariable(int it)
{
key[it] = false;
obj[it]Type = 0;
obj[it]CurAmmo = 0;
obj[it]MaxAmmo = 0;
obj[it]NextFire = 0;
this.GetComponent<UiCoordination> ().DestroyAbilityImage ([it]);
}
Answer by Dave-Carlile · May 11, 2016 at 06:49 PM
"Class" and "array" are the words you're looking for.
class Weapon
{
public int Type;
public int CurAmmo;
public int MaxAmmo;
... etc...
}
You can then create an array of you weapons...
Weapon[] weapons = new Weapon[5];
Create your weapons...
weapons[0] = new Weapon();
weapons[0].Type = 0;
weapons[0].CurAmmo = 10;
...etc...
And you can access a particular weapon by its index in the array. Reading up on arrays and classes and such will help you get the rest of the way.
Use [System.Serializable] if you want to see your class in inspector.
[System.Serializable]
class Weapon{
public int Type;
public int CurAmmo;
public int $$anonymous$$axAmmo;
... etc...
}
Weapon[] weapons = new Weapon[5];
Answer by Flaring-Afro · May 11, 2016 at 06:56 PM
What you are looking for is a Struct. I'm not the best at explaining code but this site is pretty good at breaking down concepts. It's basically a variable of variables and you could make a list of these.
Struct should be used for very specific things, even more if you can't explain it. It's best to use class if you don't know the difference.