I have an object that moves about and must access the script of any object it collides with. Instead of going through and listing every script (Type), I was wondering if there was a way I could detect and use the type based off what I COULD receive.
void OnCollisionEnter2D (Collision2D other)
{
GameObject enemy = other.gameObject;
string enemyTagDetect = other.gameObject.tag;
//All the script names end in "Controller". e.g. "GoblinController".
Type EnemyScriptType = Type.GetType(enemyTagDetect + "Controller");
//GoblinController(Type).
EnemyScriptType enemyScript = enemy.GetComponent<EnemyScriptType>();
enemyScript.Health -= damage;
}
I may be understanding the use of Type.GetType or the Type declaration of “Type”.
How do I use a string value as the “Type” of the expected type’s name?
You need to use Reflection.
Rather than explain it, I would recommend looking at MSDN and the loads of tutorials online about Reflection so that you understand how it works, what you would use it for and why. It’s magical pixie dust stuff but you have to understand it or you’ll come back to it 5 minutes later and be able to read the code you just wrote.