How can I get "Script" component of GameObject without specific script name?

Sorry for posting such an elementary question.
In my code, there are multiple different GameObjects those have same name of public variable inside. For example, I have objects of “Orc” and “Dragon”. Both scripts have same public variable like “HP”.
Then, I am trying to operate the variable “HP” when a fire-ball hits to either Dragon or Orc.
Each Dragon and Orc have differnt name script component <dragon_cntrl> and <orc_cntrl>. Therefore, I want to get the component by type, not by name. (I want to apply universal code either or any type of enemy like below.)

GameObject goEnemy = collision.gameObject;
goEnemy.GetComponent(typeof(script)).iHP--;

But 2nd line does not work with an error “The type or namespace name ‘script’ could not be found (are you missing a using directive or an assembly reference?)”.

Do I need listing up all characters script name like below?

goEnemy.TryGetComponent(<dragon_cntrl>).iHP–;
goEnemy.TryGetComponent(<orc_cntrl>).iHP–;

Thanks for your help in advance!

1 Like

You can use a base-class (such as MonoBehaviour or Component).
Though you’ll probably want to do GetComponents<>, so you can get all of the MonoBehaviours & then loop through them.

If you want to get a .iHP from the script, you might want to have the Scripts implement an Interface instead. Then you can do GetComponent();

public interface IHealth
{
  void ChangeHealth(int change);
}

public class Class1 : MonoBehaviour, IHealth
{
    private int health;

    void ChangeHealth(int change)
    {
        health -= change;
    }
}


public class Class2 : MonoBehaviour, IHealth
{
    private int health;

    void ChangeHealth(int change)
    {
        health -= change;
    }
}


public class ManagementScript : MonoBehaviour
{
    void DoStuff(GameObject go)
    {
        go.GetComponent<IHealth>().ChangeHealth(10);
    }
}
2 Likes

@SF_FrankvHoof ,
Thank you very much for educating me. It works and I learned!