Use variable value in GetComponent<>

Hi guys rather quick question.

Wanted outcome would is:

collider.gameObject.GetComponent<blabla>.posX=123;

However following code isn’t working:

var1="blabla"
collider.gameObject.GetComponent<var1>.posX=123;

Can someone point me in any direction how could I achieve that?

While GetComponent has a version that takes a string, listed here Unity - Scripting API: GameObject.GetComponent. It’s generally not a good idea to use the string version due to lack of compile time checking.

yeee but none of these work, tried:

collider.gameObject.GetComponent(var1).posX=123;
collider.gameObject.GetComponent("var1").posX=123;
collider.gameObject.GetComponent(typeof(var1)).posX=123;

Whatever you pass in needs to identify a component type, or an interface type. No matter if you use a generic type parameter, a System.Type or a string as argument.

How do i do that?

In your example that would be

GetComponent("blabla") as blabla;

Ah, I get it. You want that to be dynamic. Hold on…

1 Like

Ok, it’s a bit more roundabout, but this will work:

public class typeTesting : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        string tString = "blabla";
        Component testing = GetComponent(tString);
        // now do testing 
        if (testing is blabla) {
            blabla b = testing as blabla;
            b.t = 1;
        }
    }

}

public class blabla : MonoBehaviour{
    public int t = 0;

}

You need to have those component types or interface types. They need to be actual types in the .NET framework, in the engine, in plugins or your own source code.

For example, the built-in type Transform.
You can use GetComponent<Transform>, GetComponent(typeof(Transform)) and probably something like GetComponent("Transform") (unless the full-qualified name is required). I strongly recommend not to use the overload that takes a string. It’s the worst thing you can do.
Yes sure, there’s the shortcut “.transform” but it’s all about the principle.

Besides that, I kindly recommend to start with C# basics first. You seem to miss fundamental concepts. Without these concepts you will have a very hard time coding anything.

2 Likes

While I agree 99% with @Suddoha there are rare (and far in-between) edge cases (happened to me when I wrote an editor extension) that made the code a lot more extensible when I used GetComponent(string).

In general, though, I regard using it as a sure sign that something in my design was amiss… :slight_smile:

… isn’t GetComponent(string) a relic from the pre-Generic aera of C#?