- Home /
How to reference a variable in another script based on string in c#
That description was strange, but that was the best way I can think of to describe what I am trying to do.
I have a script called ammoCase and it contains a series of int's called ammo1, ammo2, ect. I have a script on my guns that refers to this script by
_ammoCase = transform.parent.GetComponent<ammoCase> ();
(the gun is in a child game object). I have a series of statements that refer to these variables. For example:
if (_ammoCase.ammo1 >=0){
}
I would like the type of ammo used to not be hard coded, but refer to a string to determine which ammo to use. I have tried something like this:
public string ammoType = ammo1;
void Start () {
_ammoCase = transform.parent.GetComponent<ammoCase> ();
}
void Fire () {
if (("_ammoCase." + ammoType) >=0){
Do something;
}
}
But I have had no luck so far. If you know how I can get this to work, it would make my day. Thank you for reading my question.
You would need Reflection for that, but that would be a pain in the ass :P Why you don't simply store ammo1, ammo2, etc in an array "ammos" inside AmmoCase? So ins$$anonymous$$d than calling _ammoCase.ammo0, you would call _ammoCase.ammos[0], and thus you could use ifs, whiles, fors, and all that stuff, since you have an integer to work with ins$$anonymous$$d than a series of variables.
Your answer
![](https://koobas.hobune.stream/wayback/20220613133737im_/https://answers.unity.com/themes/thub/images/avi.jpg)