- Home /
This question was
closed May 07, 2017 at 02:21 AM by
OfficialCoatsee for the following reason:
The question is answered, right answer was accepted
Question by
OfficialCoatsee · Apr 09, 2017 at 07:19 AM ·
c#variablesmethodmethods
Calling a variable based on a variables name?
I am trying to call a specific variable, but I am trying to call it by providing its name FROM another variable.
I don't exactly know what to search to find it, I tried Reflection and reviewed Multithreads, but none of it helps me.
I have an inventory handling script, that displays the inventory, and I am trying to do this...
Calling Method:
Texture2D inventory_1_texture; //creates a new empty texture variable.
int inventory_1_id = 1; //this sets the item object to 1.
//call the following...
inventory_1_texture = game.GetComponent<EveryItem>().item_ + inventory_1_id + _icon; //load icon from the preset item variable.
In the EveryItem script, I have public variables set for each item id, like so.
public string item_1_name = "Logs";
public Texture2D item_1_icon;
public string item_2_name = "Ash";
public Texture2D item_2_icon;
public string item_3_name = "Bow";
public Texture2D item_3_icon;
How can I call these variables with a code similar to my calling method? Based on a dynamic variable?
Comment
A dictionary? I will look in to this quickly, thank you.
Best Answer
Answer by OfficialCoatsee · Apr 09, 2017 at 11:07 AM
I used arrays instead.
public int[] inventory_slots = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//contains item id.
Texture2D[] icons = game.GetComponent<ItemHandler>().icons;
//get array of item icon's from ItemHandler script.
inventory_1_texture = icons[inventory_slots[1]]; //assign texture based on the id
//which is also the array position.