How to reference a function from a Component that is, itself, a variable

I have a gameObject in my scene, “CharacterA.”

CharacterA has a special only-for-him script: ReactionsForCharacterA. It has a function: Panic()

Every Character has a unique-to-them script, but all of those scripts have a Panic() function.

What I want to do is to be able to reference the Panic() function from any other script.
But I have no idea how to tell Unity which script I want, via reference (not name).

I couldn’t find anyone else ever trying to do anything this silly, so Google was no help.

I tried this, but Unity won’t let it compile (no surprise):

using UnityEngine;

public class RandomOrdinaryScript: MonoBehaviour
{
    //This variable is where the UniqueToA, UniqueToBe, &c scripts would go.
    public Component UniqueToCharacterScript;

public void CallTheirPanic()
{
    //I know what I want to ask Unity to do, but no idea how to ask it.
    GetComponent<UniqueToCharacterScript>().Panic();
}
}

I tried several variants of that line.
I tried prefixing it with gameObject..
I tried turning things into strings
I tried shuffling and removing (sorts) .o.f. things.
None of them worked.

But then I thought, “This may not be possible. Let me see if anyone knows in the forums,” since a few hours of internet searches proved fruitless.

Does anyone know? Can this even be done?

What I suggest is you look at setting up an interface. Then, you can grab that interface and call panic on it instead of whatever script is on that character.

Either use the same base class for the unique character classes and have them all derive from that or implement an interface.

1 Like

Quick example, excuse any typos or other weirdness. You’ll also need to create the Interface itself (in this case ISpeak) but there are a ton of examples on that, so I’ll leave that to you.

public class Dog: MonoBehaviour, ISpeak
{
   public void Speak()
{
}
}

public class Cat: MonoBehaviour, ISpeak
{
   public void Speak()
{
}
}

public class AnotherScript: MonoBehaviour
{
   public void TargetSpeak(GameObject target)
{
    target.GetComponent<ISpeak>().Speak();
}
}
1 Like

Oh gosh I had no idea this was a “thing.”

Thank you!

I swear, a single tutorial that just had a screenshot of a “Hello World” script with lines pointing at the different parts and saying “You know what else could go here?” would solve, I think, half of all nooby forum posts like mine…