Using GetComponent to get a script using a string

user2740515 picture user2740515 · Aug 18, 2014 · Viewed 7.5k times · Source

Using the following code I am able to get the Script from "SMG" and apply it to the weaponObject:

weaponObject = GameObject.FindGameObjectWithTag(SMG).GetComponent<SMGScript>();

Is it possible to action something like the following and if so, how?

string variable = "SMG";

weaponObject = GameObject.FindGameObjectWithTag(variable).GetComponent<variable>();

I want to have a number of scripts that I can apply to weaponObject dependant on a variable.

Answer

apxcode picture apxcode · Aug 18, 2014

Since I see the weapon has a different name than the script you will need 2 variables.

string variable = "SMG";
string scriptName = "SMGScript";
GameObject.FindGameObjectWithTag(variable).GetComponent(scriptName);

This is not efficient.


Solution

What you want to do is have a parent class and all your weapons will inherit from it.

public interface Weapon
{
}

Then you create all your weapons like this example:

public class M4 : MonoBehaviour, Weapon
{
}

public class MP5: MonoBehaviour, Weapon
{
}

When ever you want to grab the script component you can simply use this:

string tag = "Weapon";

Weapon w = GameObject.FindGameObjectWithTag(tag).GetComponent(typeof(Weapon)) as Weapon;