2
\$\begingroup\$

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

\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.