Writing Interfaces in Unity

For today’s article, I’ll be going over how I used Interfaces when developing my shoot ’em up game in Unity.

Full Code Source:

The Game:

What are Interfaces?

An interface in C# serve as a data contract where all classes to fulfill when implementing. The I in front of Example isn’t required to define the interface but is part of a naming convention I like to follow. The syntax looks something like the following below:

Unlike a class, interfaces don’t need explicit function definitions written in this file. Instead, we let the classes that implement these interfaces to define the exact implementation details.

Why Interfaces?

Interfaces are useful when we want to abstract away the implementation details of a class and declare the interface variables within our Component classes. This allows us to swap between different components that implement the interface in Unity without having to change the component’s type in the variable declaration section in the Unity Component scripts.

We use interfaces for this game to define 2 commonly used behaviors in the game:

  • Movement (IMovable)
  • Shooting Patterns (IShootable)

The following lines:

movable = GetComponent<IMovable>();
shootable = transform.GetCompnentInChildren<IShootable>();

As long as the game object has a component that has an IMovable interface implemented and a component in its child game object that has an IShootable interface implemented

Down Mover can be replaced with another IMovable component
Single Shot is an IShootable component

Using interfaces has allowed me to create a modular system where I can mix and match different movement and shooting pattern components when building different enemy types you’ll see in the game link above.

Thanks for reading! :)

Software Engineer