- Home /
Accessing incremental gameobject names, ie obj1, obj2, obj3, how?!
Despite reading all night various questions that seem quite similar but end up just creating incremental game objects I've had to resort to asking... I'm returning to programming after a good few years away so this is something I have done in the past in C but cant even remember what to call it! I have a number of buttons underneath images and an array tracking the status of those images, so for example an image could be available to buy in which case the button needs to say 'buy me' or ready to sell 'sell me' or empty 'empty'. Each button's text element (.text) is named Available1, Available2, Available3 and each button is named Available1button, etc. So I'm having problems working out the syntax to address a button's text element within a for loop, that is not directly typing in Available3.text (which does work), I want to address it Available+x.text where x is the for count. I thought it would be something like "Available"+x.text = "Sell me"; Many thanks in advance.
Answer by tanoshimi · Nov 06, 2016 at 12:03 PM
Trying to build dynamic references like this is frowned upon, if not impossible, in most modern programming languages. The correct solution to your problem is to add all of your elements to an array ( GameObject[] AvailableItems;
), and then access each element using an index accessor: AvailableItems[0]
, AvailableItems[1]
etc. etc.
Yeah I was starting to think this but at the same time don't really see why, at the end of the day I'm simply asking the game to access a location and to be able to decide which location based on an index...so basically an array...when you think about compilers reducing code down to hex/assembly in the end it's stored as a number, I'm NOT trying to alter the name that the compiler has been given I'm trying to construct the correct name...but hey ho it's a mute point and I'll do it the hard way and build a list in an array. Thanks for the answer.