- Home /
Can i give GetComponent a variabel instead of a scriptname?
Is it possible to give GetComponent a string? Because I have multiple vehicles and they all have their own controll script.
My idea:
public GameObject tank;
public string scriptName = "TankController";
tank.GetComponent<scriptName>().enabled = true;
Answer by CHPedersen · Aug 13, 2013 at 12:52 PM
Yes, if you use the string version of GetComponent instead of the generic version:
public GameObject tank;
public string scriptName = "TankController";
((TankController)tank.GetComponent(scriptName)).enabled = true;
Or, if you just need the enabled property:
public GameObject tank;
public string scriptName = "TankController";
((MonoBehaviour)tank.GetComponent(scriptName)).enabled = true;
This should work just fine as long as you supply the name of a script that actually exists, of course. Beware that it's generally safer to use the generic version where possible, since a lot of potential errors can be caught at compile time instead of producing more obscure bugs which will be harder to catch later on. But if your scenario calls for it, it's perfectly fine to use the string version.
And how can i disable it? I don't get a match for disabling after the bracket
Then i get this errror: UnityEngine.Component' does not contain a definition for enabled' and no extension method
enabled' of type `UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
Yup, that's one of the disadvantages of using the string version. With the generic version, you get the actual type of the script through the generic type parameter, and it automatically has the enabled property because all scripts inherit from $$anonymous$$onoBehaviour, which is where it is defined.
But with the string version, you don't get your own script type or even $$anonymous$$onoBehavior, you just get the most base class it knows for all components, namely Component. So now, you have to static cast back to your own script to get to .enabled. I've updated my answer accordingly.
for one vehicle it works, but when i try to go in the second vehicle i get this error.
InvalidCastException: Cannot cast from source type to destination type. With this ((VehicleControll)car.GetComponent(scriptname)).enabled = true; i have the same problem than before.
For Info: The second Vehicle dont have the script VehicleControll, so it would only work with vehicles which has vehicleControll and not with planeControll(as example)?
i would like to to manage every vehicle with the same enter/exit script.
I think it would be the best, when i work with bools and check in front of what vehicle i stay?