- Home /
Identify and Use Unknown Types
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?
I think it would be easier if all those objects inherited from an abstract base class with maybe an enum for their type, if even needed. After all you'll want to use a method /variable from that object, so you'll need to know atleast something about it. $$anonymous$$y suggestion is to use virtual or abstract methods/properties from the base class. Or as a different approach, maybe even a separate component for health in your example.
ValooFX makes a good point, a lazier way to fix your script would be to use other.Send$$anonymous$$essage("ChangeHealth", -damage);
and put a ChangeHealth(float change)
function in every enemy script...
I was thinking about messing with abstract classes or Interfaces to access all of the information. It's not really the route I want to take, but I'll definitely try it if there is a better design approach.
Answer by LaneFox · Jul 28, 2015 at 11:33 AM
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.