I am trying to use a variable in the parameter of gameObject.GetComponent("var's Name").

The main problem is that the GetComponent() parameter doesn’t work if I use a variable of type String in it, but I need to use a variable for the GetComponent() parameter because in my game the character picks up different weapons and I need to use a variable that’s always equel to the weapons’s script’s name.

Here’s a part of my script: (JS)

//The variables I used:
var weapon : Transform;
//The script name on any of my weapons will always be the weapon's name with "Script" added at the end.
var weaponScriptName : String = weapon.gameObject.name + "Script"; 

//The script I need to use, but it doens't work:
weapon.GetComponent(weaponScriptName).attack = true;

//The script that works but only if I hardcode the weapon's name in every case.
weapon.GetComponent(SwordScript).attack = true; //weapon in this case is "Sword".

You are out of luck doing it this way. While GetComponent() with a string works, the type it returns is ‘Component’, and the Component type will not have an ‘attack’ variable. You can cast the result, but you cannot use a variable string cast. So solving it this way would require a case statement or it like that either explicitly use the type or explicitly uses the cast.

The typical solutions to this kind of problem is to have a base class like ‘Weapon’ that has an attack variable. All the weapons are derived rom the base class.