GetComponent("string") not working like GetComponent<>() ?
Long story short, I am trying to access a script in a UnityObject from another script. In my game, the player has to type words in order to perform actions on an object, so I have a hashtable on this object which contains key/value pairs such as {"examine", "PlayerActionExamine"} etc. In this case, PlayerActionExamine is a script attached to this object.
I can access this script's variables and methods just fine by using
gameObject.GetComponent<PlayerActionExamine>().nameOfTheVariableOrMethod
however if instead I use
gameObject.GetComponent("PlayerActionExamine").nameOfTheVariableOrMethod
the variables and methods cannot be found.
Is there some kind of workaround or solution to this? Because my hashtable contains strings, I can only really use the second variant of GetComponent but it seems to not work for some reason.
Thanks.
Answer by highpockets · May 30, 2019 at 08:18 AM
I don't know what type "nameOfTheVariableOrMethod" is, but I assume it is a string. Anyhow, you can put your value in a variable and compare it to "PlayerActionExamine"
if( valueString == "PlayerActionExamine" )
{
string newString = GetComponent<PlayerActionExamine>().nameOfTheVariableOrMethod;
}