# How can I grab the script component of a collided object without knowing what script it is?

CalculateDamage() is an animation event called at a point during the character's animation in my 2D game. The commented out code is before I realized that not all of my pirates will be of class MeleePirateUnit, so I'm trying to do things more generically here. My order of inheritance is like so:

MonoBehaviour > Unit > MeleePirateUnit, RangedPirateUnit.

So sometimes, the collidedobj is a MeleePirateUnit, sometimes it's a RangedPirateUnit, etc etc. How do I set pirateUnit to the correct type of the script component of my gameObject? I thought just getting component of type monobehaviour would work since RangedPirateUnit and MeleePirateUnit both derive from monobehaviour but I'm getting an error of

Assets/Scripts/Combat Scene/RangedPirateUnit.cs(72,56): error CS1061: Type UnityEngine.MonoBehaviour' does not contain a definition forhealth' and no extension method health' of typeUnityEngine.MonoBehaviour' could be found (are you missing a using directive or an assembly reference?)

public void CalculateDamage(){
if (!isDestroyed){
var pirateUnit = collidedObj.GetComponent<MonoBehaviour>();
//MeleePirateUnit pirateUnit = collidedObj.GetComponent<MeleePirateUnit>();
pirateUnit.health = pirateUnit.health - (damage - pirateUnit.defence);
if (pirateUnit.health<=0){
Destroy(pirateUnit.gameObject);
isDestroyed = true;
didAttack = false;
}
}
}

• Unity favours the principle of Composition Over Inheritance, so anytime you're using inheritance, it's worth asking whether you could accomplish the task by composition instead. In this case, you could have a Health component that handles HP & death, and guarantee that all unit classes have one using [RequireComponent()]. You don't need to do it this way, but it's often easier to go with the flow of how Unity likes to do things, and the modularity can have unexpected side benefits (like being able to give health to destructible objects like crates or breakable walls, which aren't units) – DMGregory Jun 9 '15 at 2:45

Assuming your Unit class has the health var, try:
Unit pirateUnit = collidedObj.GetComponent<Unit>();