Convert string to array name?
is there a way to use a string as an array name? For example I have an array of game objects called Gems and another array called Rubys, in the player script is a string of what the player needs to catch that changes, so when that string is Rubys I want to spawn from the Rubys array and when it is Gems I want to spawn from the Gems array. Thing is I did a if(player.wordToCatch == "Rubys") { Instantiate(Rubys[Random.Range(0, Rubys.Length)], position, Quaternion.Identity); } else if(player.wordToCatch == "Gems") { Instantiate(Gems[Random.Range(0, Gems.Length)], position, Quaternion.Identity); }
but I have about four different arrays and my game is glitchy I feel like its from this, if I could just use the player.wordToCatch as the array name I'd eliminate so many lines of code. Like
Instantiate(player.wordToCatch([Random.Range(0, player.wordToCatch.Length)], position, Quaternion.Identity);
but it won't work because obviously player.wordToCatch is a string, can I cast it or convert it or something so it knows I'm trying to reference that array?
Turning strings into variables is almost always a bad way to solve any problem. It's like asking how many loose bananas can fit in your car -- whatever it is you think you need to do that for, there's a better way.
In Unity, some people use tags, or attached scripts, to deter$$anonymous$$e what sort of item you've selected.
So do you think my current way is better performance wise?
Use a Dictionary string-array or do it the hard way and use System.Reflection to find the right Field.