GameObject.GetComponent and Concatenation

Hi all,

Is it possible to build a .GetComponent path by using other variables?

I have costumes that can be unlocked which all share the same script, I give them a number in Editor.

public float ThisSkinNumber = 3;

On a different GameObject I save whether these objects have been unlocked.

public bool Sprite3 = false;

and of course, can access it on the costume script like so bool skinUnlocked = Save.GetComponent<Save> ().Sprite3;

I’m wondering if I can use the costume number float in the GetComponent? Something like this - but something that works.

bool skinUnlocked = Save.GetComponent<Save> ().Sprite + ThisSkinNumber;

Thanks.

There are ways but why complicate it when you could just make the sprite component in your save class an array and access a set index or create a method to access the sprites via a value or string?

2 Likes

Not without reflection, which is not a path you want to go down, trust me. Just use a collection object (List, HashSet, Dictionary) to keep track of which ones you have unlocked. Also for the sake of all that is holy I recommend using int as an identifier for this kind of thing, not float.

2 Likes

It would probably be better to group these common values under one struct or class, such as:

[Serializeable]
public struct Costume {
   public int skinNumber;
   public bool unlocked;
   //Other fields you might need (Sprite?)
}

Then in your other script, you could create a collection of Costumes, and each one can be looped through to compare if they’re unlocked:

Costume[] costumes;

void Example() {
   for(int i = 0; i < costumes.Length; i++) {
      if(costumes[i].unlocked) {
         //etc.
      }
   }
}
2 Likes

Nice, thank you for the help guys.