Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GetComponent to get a script using a string

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.

like image 773
user2740515 Avatar asked Oct 21 '22 03:10

user2740515


2 Answers

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;
like image 195
apxcode Avatar answered Oct 22 '22 17:10

apxcode


Yes it is possible to use variable on GetComponent, like this:

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

Even though that it is not recommended due to performance reasons, as stated here.

However the thing I'm not sure is how you define this weaponObject, as the script you get from GetComponent may vary and your variable type must be the same as the script you get.

My suggestion is to put all weapons inside a script and give it a type variable (ex: type 1 is machine gun, type 2 is hand gun, etc) to represent each weapon. That way you can get the script like above and find out what type of weapon you're getting by accessing the type:

int weaponType = weaponObject.type;
like image 26
Jay Kazama Avatar answered Oct 22 '22 16:10

Jay Kazama