Get Parent Class From Other Script

Hi,

I have four scripts, Wall, Player, Enemy, and GamePart. Both Player and Enemy inherit from GamePart. Inside of GamePart there is a variable health. When an object enters an area i would like to deal damage to him, but i dont know if its an enemy or a player. I am aware that i could check for it using:

if(enterer.GetComponet<Player>())
//Action
if(enterer.GetComponet<Enemy>())
//Action

However i may add more objects that inherit from GamePart and i would like to do it more dynamically.

Basically i would want to do

enterer.GetComponet<GamePart>().health--; 

But i get a object reference not set to an instance of an object

As you noticed, GameObject.GetComponent will only work with a specific component name and disregards inheritance. If you would like an easy check for all types of moving objects that may enter the sphere, try creating a script that all of them will have, instead of using inheritance. Then, you could always check for that specific component.

Health component = enterer.GetComponent<Health>() as Health; 
if(component != null)
{
    component.health--;
}

You could make your health method static, I often find this more useful for me. Here is a brief example:

public static int health = 100;

public static void Damage()
{
health -= 5;
}

Then in your other class call your method by:

classname.Damage();

Hope this was helpful :slight_smile: