Introducing the C# interface

What is an interface? You might be familiar with this word. Else go ahead and look it up in a dictionary. Right! Didn't help me much either.

Let's focus on some electronic devices as examples. For example, a game controller for a game console. The buttons, the shape, and so on, that's an interface. It's how you are allowed to interact with the game. How about a TV remote? That's an interface. It's how you are allowed to control the TV. How about a smartphone? A few buttons and a touch screen, perhaps some motion. That's an interface. That's how you are allowed to use the device.

How about the Unity game engine? Does it have an interface? Sure it does. It's right there on your computer screen. It's called the User Interface.

There's another part of Unity that has an interface. It's called the Scripting Reference.

What???

Sure, think about it. In order for your GameObjects to have certain behaviors, you have to use the classes available in the Scripting Reference. You have certain variables and methods in each class available for you to use. That's an interface, a programmer's interface. Even more technical, it's called an Application Programming Interface (API).

Every time you create a script, you get to control whether a variable is private or public. If you make it public, you have stated that the variable is an interface on that class. It even appears in the Inspector panel, which is another interface.

How about methods? If it's public, then it's an interface point that can be used from other classes.

The State Machine and the interface guarantee

All States have to incorporate particular methods that the StateManger class can call. Therefore, the States have to guarantee that these methods are implemented, otherwise the State Machine won't work.

Well, since you write the code for your classes, can't you just remember and make sure these required methods are implemented on each State? Sure, that's possible, but it's not a guarantee, is it? Suppose your game has ten possible States. There's just too much room for spelling mistakes, or just plain forgetting to implement the required methods.

C# does have a way to guarantee that the required methods are implemented in each State by using a C# interface. I know, I've been using the general word interface a lot here, but that's what it's called, an interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.44.143