Categories
Coding Tips Game Development Unity Tips

Unity C# | Interfaces, What are they & how do you use them?

What are interfaces?

So, in my own words they are a way of ensuring a class has particular properties and methods in them. You’ll commonly hear that they are sort of like contracts which is also a good explanation of what they are. When I was learning what interfaces were and their use case, the internet didn’t really give me any solid examples. So, this is mostly to sum up what they are, how to make them and some examples where they could be used.

How do I make an interface?

Making an interface is super simple, in Unity you just make a normal C# Class, a common naming convention you’ll see a lot is to prefix your interface class name with the letter I followed by the class/interface name. For example: IObject, IWeapon, IGun, IItem, IDamagable, IInteractable etc. Once you’ve created the class, open it in your editor of choice and replace the class definition with the word interface like so:

// Before
public class IExample
{
}

// After
public interface IExample
{
}

Depending on your IDE this may change the class name to a different colour, commonly yellow. At this point you now have an interface class that you can use, but there is nothing in it right now, so it won’t do anything. That is what we’re going to do next.

What do I put into an interface?

So, now you have an interface, what do you put into it? This really depends on what you need the interface to do. However, you can only define properties and methods in an interface, none of the actual functionality is put here, we’ll get to that in a bit. All properties and methods in your interface will be public by default, so your don’t need to define the public status for anything.

int PropertyExample { get; set; }
string AnotherPropertyExample { get; }
float YetAnotherPropertyExample { set; }

void MethodExample();
int ReturnMethodExample();
void MethodWithParameters(int a, float b);

To pick an example, let’s say you have a game with a lot of items that need different functionality when they are equipped, used or dropped. We can also assume each item would need a name and a description which could be in a scriptable object, but for this example we’ll have them be separate. So, this interface would be something like this:

public interface IItem
{
    string ItemName { get; set; }
    string ItemDescription { get; set; }
    void EquipItem();
    void UseItem();
    void DropItem();
}

How do I use my interface?

To use an interface, you simply add it after your classes inheritance like so:

public class Example : MonoBehaviour, IExampleInterface
{
}

You’ll find that once you define that a script inherits an interface that your IDE will complain saying that your class does not contain an implementation of all the properties and or methods that are defined in that interface. This is because you class now is required to have an implementation for everything in the interface, so like a contract, your class is now required by that contract to have those properties and methods, if that makes sense.

To go back to our item example, a blank class which is defined as an Item by the IItem interface would look the example below, Note that everything we defined in the interface is there and is public. You can now add your functionality to each method as needed for that item, you can inherit as many interfaces as you like and use a base class for common functionality that is the same across a lot of items.

public class Book, MonoBehaviour, IItem
{
    public string ItemName { get; set; }
    public string ItemDescription { get; set; }


    public void EquipItem()
    {
        throw new NotImplementedException();
    }

    public void UseItem()
    {
        throw new NotImplementedException();
    }

    public void DropItem()
    {
        throw new NotImplementedException();
    }
}

How are interfaces useful?

Interfaces are super useful for a variety of projects but ultimately it up to you on where you use them. A simple example could be a basic shooter, where you could have interfaces for Health, Damage, Guns, Interactions etc. What I find makes them useful is when you need to call a method like Shoot on a gun, but each gun has a different shooting functionality, like a pistol, rifle, shotgun and grenade launcher would have slightly different methods for firing but you don’t want to have to check which one the user has and call that classes particular shoot method. Instead, you would just call the interface method and have each gun class inherit the interface. Below is a before/after example to showcase how much neater this implementation is when calling the shooting method.

// This example assumes you have a Enum & GameObject reference for the active gun the user has equipped.
// Before
private void FireGun()
{
    switch (gun)
    {
        case Guns.Pistol:
            activeGun.GetComponent<Pistol>().Shoot();
            break;
        case Guns.Rifle:
            activeGun.GetComponent<Rifle>().Shoot();
            break;
        case Guns.Shotgun:
            activeGun.GetComponent<Shotgun>().Shoot();
            break;
        case Guns.GrenadeLauncher:
            activeGun.GetComponent<GrenadeLauncher>().Shoot();
            break;
        default:
            throw new ArgumentOutOfRangeException();
    }
}


// After
private void FireGun()
{
    activeGun.GetComponent<IWeapon>().Shoot();
}


// After - With a cached array/list of IWeapon for each gun setup before use, Ideal for performant code and GC. 
// Assumes weapons is an array of IWeapon from each gun in order and gun enum is set to the active gun.
private void FireGun()
{
    weapons[(int) gun].Shoot();
}

Closing Thoughts

With any luck you now have an idea of what interfaces are and how to use them. If you need more examples and another explanation then I can highly recommend this video which covers the topic in a really friendly and digestible way without been really long. Hope this helped you, feel free to comment below with your thoughts and feedback on this post, as I plan to make more as expand this blog.

One reply on “Unity C# | Interfaces, What are they & how do you use them?”

Leave a Reply

Your email address will not be published. Required fields are marked *