Skip to content

Instantly share code, notes, and snippets.

@charlieamat
Last active September 30, 2021 19:00
Show Gist options
  • Save charlieamat/5d2c501586b5a864efd0c9b12f5f2fe7 to your computer and use it in GitHub Desktop.
Save charlieamat/5d2c501586b5a864efd0c9b12f5f2fe7 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Composition vs Inheritance (3)
  • Create InteractionHandler.cs
    • Let's try a compositional approach instead of hierarchical
    • We're going to compose our interactables with a list of handlers
    • Each handler will represent a specific behavior
  • Convert Interactable to a non-abstract class
  • Add a private InteractionHandler[] field called _handlers
  • Add a for-loop for _handlers in Interact()
  • Add a call to _handlers[i].Interact() to the for-loop
  • Implement the Start() method
    • Now all we have to do is populate our handlers at the start of our game
  • Initialize _handler using GetComponents<InteractionHandler>() in Start()
  • Switch to Unity
  • Update the Scene and verify the behavior
public class Interactable : MonoBehaviour
{
private InteractionHandler[] _handlers;
public void Awake()
{
_handlers = GetComponents<InteractionHandler>();
}
public void Interact()
{
for (var i = 0; i < _handlers.Length; i++)
{
_handlers[i].Interact()
}
}
}
public class InteractableAchievement : InteractionHandler
{
public Achievements Achievements;
public string Identifier;
public void Interact()
{
Achievements.Track(Identifier);
}
}
public class InteractableItem : InteractionHandler
{
public Inventory Inventory;
public string Item;
public void Interact()
{
Inventory.Add(Item);
}
}
public abstract class InteractionHandler
{
public abstract void Interact();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment