# How to reference and call a function from different script ?

I've a script : Toy .

Depending of toy "type" i need to activate different feature.

For instance, for "Police-Car" i need to activate Siren, for "Truck" i need to activate horn .

I don't want to re-engineer my code creating a classic way like:

Toy Class

• Truck : Toy

• Police-Car : Toy

So I want to call a generic public function "Activate", existing in Truck, Police .. from my Toy class.

How can i reference different script ( PoliceCarScript, TruckScript) inside Toy , so i can launch the Activate public method of PoliceCarScript, TruckScript ?

Thanks

You want to take advantage of polymorphism, and not inheritance. Create an interface, such as IActivatable. Truck and PoliceCar would then implement IActivatable instead of inheriting from it.

public interface IActivatable {
void Activate();
}

public class PoliceCarScript : MonoBehavior, IActivatable {

//must be public
public void Activate() {
//This method must be present in everything
//that implements IActivatable
}
}


GetComponent() works with interfaces, so you should be able to then call anything attached that can be activated with GetComponent<IActivatable>().Activate();.

The advantage of using this over inheritance (which I assume is what you meant by the "classic way") is that the classes can be used in place of each other without expecting anything in common with the implementation details. It is basically a promise that every class implementing IActivatable has an Activate method, even if each Activate method looks very different from the others.

Here's a video that helps explain it better: https://unity3d.com/learn/tutorials/topics/scripting/interfaces