How to use different types of scripts with an override function.

I have a Motor script that needs to call a Motion function from one of several types of Motion classes. So basically, one type of character might use the standard Motion script, while another character might use a SuperSpeed motion script that overrides the standard Motion class’s main Motion function.

How can I tell my Motor class which type of Motion class to use?

It sounds like you want a virtual function.

public class Base {
     public virtual void SomeMethod () {
          Debug.Log("Base Method Called");
     }
}
public class DerivedA {
     public override void SomeMethod () {
          Debug.Log("DerivedA Method Called");
     }
}
public class DerivedB {
}

and here’s an example of the implementation:

Base b = new Base();
DerivedA dA = new DerivedA();
DerivedB dB = new DerivedB();

b.SomeMethod();
dA.SomeMethod();
dB.SomeMethod();

Outputs

“BaseMethodCalled”

“DerivedA Method Called”

“BaseMethodCalled.”

In a virtual function, the child class can override the parent’s implementation of the method. Otherwise the parent’s method is called. This is helpful for things like this include places where you need a polymorphic behavior Another example would be something like Animal.Bark(). You want all animal to be able to bark but they all make a different sound so you would need to override the base classes behavior. Note Animal could likely be abstract, but just for examples sake.

Virtual functions shouldn’t be confused with abstract functions and/or classes. Abstract classes are classes that cannot be instanced and are designed to be inherited from by other classes. Abstract methods declared in abstract classes must be overridden by the inheriting class similar to how interface methods must be given a body in the implementing class.

Virtual calls have a small performance decrease but it usually won’t matter.

I would avoid where it’s possible the use of inheritence in Unity because Unity uses the component pattern.
Is it not possible for you to define public fields in your motion script that would change its behaviour (e.g. MAxAcceleration, MaxSpeed, …)?
There are several advantages in using public field:

  • they can be changed directly in the inspector even in play mode-
  • they are serialized with the scene
  • they can be changed dynamically by other scripts during the game-