Using variable to access a script variable with GetComponent

Hi Guys,
given the below script

string var = “variable1”
gameObject.GetComponent().var
is there and easy way to use a string var to access a variable into a given script?

Of course this is a simple case but I have my string variable changing based on the variable i need to access.

Thanks to anyone who can figure this out!

GetComponent does offer access via string. So GetComponent(var). You will have to cast the returned component → as MyTypeHere

From the Docs:
Returns the component with name type if the game object has one attached, null if it doesn’t.

It is better to use GetComponent with a Type instead of a string for performance reasons. Sometimes you might not be able to get to the type however, for example when trying to access a C# script from Javascript. In that case you can simply access the component by name instead of type.

Thanks for your help but i’m not very clear yet how it works, see this example below:

for (int i = 1; i == 5; ++i)
{
string pre = (“previousAction” + i);
if (GameObject.Find(obj).GetComponent().pre = “”)
{
//do something
}
}

What I want to do is accessing the different components “previousAction1”, “previousAction2”, etc…into a script without repeating the if 5 times, is it possible?

Thanks again

What I think you really want is a dictionary. You make the key a string, then you get a value corresponding to that string. Effectively it has you using a string you set at runtime as the name of a variable, even though that isn’t really what is happening.

You could also use a list or array, and then access elements of the collection by index number. It is an int instead of a string, but in your example you’re just differentiating the names by a number anyways.

for (int i = 1; i <=  5; i++)
{
   string pre = "previousAction" + i.ToString();
   if (GameObject.Find(obj).GetComponent(pre) != null)
   {
       //do something
    }
}
1 Like