I’m creating a game where I have multiple enemy types, each with their own unique script (All enemy scripts inherit from a common script called “Enemy.cs” though (Enemy.cs inherits from Humanoid.cs, not sure if need to know but it might)).
So when a bullet with an OnTriggerEnter method comes into contact with one of these enemies, and I want to access it’s variables/methods, I can’t simply say
A way of solvin this is that you can create an “Object” variable (public) and then assign the script to it, and then with myScript.GetType() you can get the “name” of the script
For this situation, I typically have an integer id attached to the base for type. This way, subclasses can then assign the proper type id, and you can look at the enemy script this way.
Similarly, you can just try casting to the specific type on GetComponent, and if it returns null, then the object doesn’t have that type of script on it.
Usually you’d inverse that - your EnemyScript would have a (potentially abstract) HitByBullet method that handled getting hit. Or you’d do what @palex-nx is suggesting, which is better design.
Still, if you want to dispatch manually in the OnTriggerEnter, you can just check the type and decide based on that. This is pretty clean in newer versions of Unity with an up-to-date C# version, by using the new pattern-matching switch statement
EnemyScript enemy = other.GetComponent<EnemyScript> ();
switch (enemy) {
case null: // aka other didn't have an EnemyScript component.
break;
case Goblin goblin:
HandleHittingGoblin(goblin);
break;
case Dragon dragon:
HandleHittingDragon(dragon);
break;
default:
Debug.Log($"Hit unknown enemy type {enemy.GetType()}");
break;
}