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.
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.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With