Back To Home

OOPS

14-03-2024


C# Interfaces: The Superpower You Didn't Know You Had in Unity

"Ever feel like your code is a tangled mess of spaghetti, with classes inheriting from everywhere and functionality all mixed up? There's a better way, my friend! Interfaces can bring order to your coding chaos – like a kitchen utensil organizer for your classes!"

Introduction :

In simple words, an interface in C# is like a rulebook that tells classes what they must do, without telling them exactly how to do it. Picture an interface as a to-do list for classes. It lists what methods and properties a class must have, but it doesn't provide the actual instructions for those methods and properties.

Here's what interfaces don't do:

  1. They don't provide any implementation details for the methods or properties.

  2. They can't be instantiated directly (you can't create an object of an interface type).

post 2

Benefits of Interfaces:

  1. Flexibility :
    Interfaces allow you to create a common set of functionalities that various classes can implement in their own unique ways. This promotes loose coupling, meaning your code becomes less dependent on specific class implementations.

  2. Polymorphism :
    With interfaces, you can treat objects of different classes in the same way, as long as they implement the same interface. This enables writing more generic code that can work with a wider range of objects.

  3. Code Reusability :
    Interfaces help you define reusable functionalities that can be shared across multiple classes, reducing code duplication and promoting maintainability.

Declaring an Interface in C# :

  
public interface InterfaceName
{
    // Method signatures (no implementation)
    void MethodName(parameters);

    // Property signatures (no implementation)
    int PropertyName { get; set; }
}

Implementing an Interface :

A class can "implement" an interface by using the implements keyword (similar to inheriting from a class):

  
public class ClassName : MonoBehaviour, InterfaceName
{
    // Implement the interface's methods and properties
}

Using Interfaces in Unity :

In Unity, interfaces are incredibly useful for creating components or functionalities that can be used by various game objects. Here's an example:

1. Define an Interface (IInteractable):

  
public interface IInteractable
{
    void Interact();
}

2. Implement the Interface in Different Classes:

  
public class Door : MonoBehaviour, IInteractable
{
    public void Interact()
    {
        // Open the door logic
    }
}

public class Chest : MonoBehaviour, IInteractable
{
    public void Interact()
    {
        // Open the chest logic
    }
}

3. Accessing Functionality Through the Interface:

  
public class Player : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            // Get the game object the player is interacting with
            RaycastHit hit;
            if (Physics.Raycast(transform.position, transform.forward, out hit))
            {
                // Check if the hit object implements the IInteractable interface
                IInteractable interactable = hit.collider.gameObject.GetComponent< IInteractable>();
                if (interactable != null)
                {
                    interactable.Interact(); // Call the Interact() method through the interface
                }
            }
        }
    }
}

In this example, the Player script can interact with any object (like Door or Chest) as long as it implements the IInteractable interface. This promotes code reusability and allows you to add new interactable objects without modifying the Player script's core logic.

Example : A bridge connecting two islands

post 2

The image is used to visually explain how an interface acts as a bridge between the class (containing data and functionality) and the outside world. Methods and properties are accessed through this controlled interface, promoting data hiding and secure code.

Here's a real-life comparison:

  1. Just like all humans have basic functions like eating, sleeping, and talking, interfaces set out basic functions that classes must have. Even though people may eat different foods or have different sleep schedules, they still meet the basic requirements of being human.

  2. In programming, interfaces work similarly. They define a standard set of functions that all objects following the interface must include, regardless of their specific features. While the exact way these functions are implemented may differ, the interface ensures that the essential functionality is there and can be used consistently.

Example 1 :-

  
public interface IHuman
{
      void Eat();
      void Sleep();
      void Speak();
}

public class Person : IHuman
{
      public void Eat()
      {
        // Implement , how a person eats
      }

      public void Sleep()
      {
        // Implement , how a person sleeps
      }

      public void Speak()
      {
        // Implement , how a person speaks
      }
}
            

Example 2 :-

  1. Let's create a basic player movement system.
  2. First, we'll define an interface called IMovable with a method called Move():
  
public interface IMovable
{
      void Move(float speed);
}

public class PlayerController : MonoBehaviour, IMovable
{
      public void Move(float speed)
      {
            transform.position += Vector3.right * speed * Time.deltaTime;
      }
}

public class GameManager : MonoBehaviour
{
      public GameObject playerObject;
      private IMovable player;

      void Start()
      {
            player = playerObject.GetComponent();
      }

      void Update()
      {
          if (Input.GetKey(KeyCode.RightArrow)) 
          {
                player.Move(5.0f);
          }
      }
}
  1. In this setup, the Move() method moves the player to the right based on a given speed.
  2. In another script, like your game manager or a player input script, you can utilize the IMovable interface to move the player without needing to know how the movement is implemented.
  3. The GameManager script locates the PlayerController script attached to the playerObject and employs the IMovable interface to move the player to the right when the right arrow key is pressed.
  4. By using the IMovable interface, you can effortlessly switch the player's movement system for a different one that also implements the interface, all without altering any code in your game manager or input script.

Similarly :-

We can create various small interfaces for different tasks, such as: IShootable, IClickable, IInteractable, IDamageable, and so on.

For instance, if we want our player to be able to shoot, we can implement the IShootable interface and define the shoot() method. Similarly, other interfaces work in a similar manner. Enemies can also utilize these interfaces if they need shooting capabilities.

Key Points to Remember :-

  1. Interfaces define functionalities, not implementation details.
  2. Classes implement interfaces to provide their specific implementations.
  3. Interfaces promote loose coupling and polymorphism in code.
  4. Use interfaces in Unity to create generic components that can work with various game objects.

Conclusion : -

In conclusion, interfaces in C# provide a powerful mechanism for defining contracts between classes, ensuring consistent behavior across different implementations. By adhering to interfaces, developers can promote code reusability, maintainability, and flexibility in their applications. Whether it's implementing common functionalities or enabling modular design, interfaces play a crucial role in modern software development.


I hope you found this blog post enjoyable!


More Blogs

See All