How to refer to a script that could be one name or another?

I have a script in which I want to make a reference of a script.

The problem is that the class I want to refer to could be either Hero or Enemy.
Hero and Enemy both inherit from my Character class (non-MonoBehaviour).

public Hero myRefScript;
public Enemy myRefScript;

So I would want to combine these two variables into one variable, and the type of the variable will depend on whether we are on the Hero or an Enemy.

Other solutions are suggesting using SendMessage but this is not very efficient.

Any other way I could do that?

Since your classes already inherit from Character, you can just make a public Character myRefScript. Write a getter for deciding if it’s a Hero or an Enemy in the Character class like this:

//in the Character class:
public virtual bool IsHero {
     get {
          return this is Hero;
          // this won't be used unless you forget to override it
     }
}

//in the Hero class
public override bool IsHero {
     get {
          return true;
     }
}

//in the Enemy class
public override bool IsHero {
     get {
          return false;
     }
}

And if you need something Hero- or Enemy-specific you can just convert it like this:

if (myRefScript.IsHero) {
     Hero hero = (Hero) myRefScript;
     //do stuff
}
else {
     Enemy enemy = (Enemy) myRefScript;
     //do stuff
}

This conversion is really fast, you don’t need to worry about it.

You could also attempt to cast to the derived class.

WhateverInheritedClass wic = GetComponent<WhateverInheritedClass>();

if(wic != null)
{
    Hero derivedHero = wic as Hero;

     if(derivedHero != null)
      {
           //Do whatever is related to hero only
          //derivedHero.DoMyStuff();
           //Possibly return here
      }

    Enemy derivedEnemy = wic as Enemy;

     if(derivedEnemy != null)
      {
           //Do whatever is related to enemy only
          //derivedEnemy.DoMyStuff();
      }
}

This offers a safe way to ensure you get the correct type and then also have the cast of the object to directly work with. Secondly, this avoids needing to create anything extra in your base/derived classes for class identification purposes.

Not positive this will work but have you tried referring to the classes by the Character class instead.
I.E public Character myRef;

I know if have done something similar in c++ before but not sure about c#.