[SOLVED]Find variable from string? GetComponent<Script>()."the component in a string";?

Hello! i’m having with a very simple problem with this:

i have a list of slots:
SlotItem1
SlotItem2
SlotItem3
SlotItem…

i thought it would be easier to search for a specific slot building the string with it’s name:

string GetSlotItem = "SlotItem" + RegEmptySpot;

Where the “RegEmptySpot” is the number, so i would ask something like:

ThisPlayer.GetComponent<Inventoryv2>().GetSlotItem();

Where the “GetSlotItem” = SlotItemX.

what is the right way of doing this?

Thanks in advance.

Personally I wouldn’t usually do it like that.

I might get a slot by index (in the list).

Or maybe have each slot know its own number and then iterate through all slots looking for that number.

Or maybe even have a Dictionary that maps numbers to slots and access in that way.

2 Likes

heard of that solution when i was googling it, i have no idea yet how to use that Dictionary function lol
but i didn’t thought it’d be necessary since i wouldn’t uso more than 6 slots.

It sounds like you’re really accessing these by a number. In which case, you definitely should use an array. Unity has a good tutorial for arrays.

2 Likes

In that case you don’t want to be using reflection, which is the other common way to access data via a string.

But seriously, just go with an array. String based programming is evil.

1 Like

Thanks for the feedback ! i’ll look into it! for what i see it is indeed very useful, makes me think about the code i already applied … like i could have done it smaller and more optimized … well, it happens, it’s not too late for changes XD

Thanks.

Thanks for the replys! it worked! i’m making a multiplayer co-op so its works but … well :smile: not perfect yet.
Just to leave some answer to help someone who might need this.

Do array. That’s it.

//You can make it as in int, string, bool, whatever.
//The [4] in this case represents the number of elements inside this array.

private string[] SlotItem = new string[4];

//To check this array, i did this:
int RegSlotHave = -1;

if (ObjName == SlotItem [0]) {
                RegSlotHave = 0;
            }
            if (ObjName == SlotItem [1]) {
                RegSlotHave = 1;
            }
            if (ObjName == SlotItem [2]) {
                RegSlotHave = 2;
            }
            if (ObjName == SlotItem [3]) {
                RegSlotHave = 3;
            }

//And then did something like this:
            if (RegSlotHave == -1)
{
//Do stuff
}

//To edit or retrieve a value from the array, i do something like:
SlotItem[RegSlotHave] = string x

//or

string x = SlotItem[RegSlotHave]

And now you should turn that repetitive code into a loop!
Not only is it less code, it also makes your code more versatile and much easier to maintain and to read.

for (int s=0; s < SlotItem.Length; s++) {
if (ObjName == SlotItem[s] ) {
RegSlotHave = s;
}
}