Skip to content

Instantly share code, notes, and snippets.

@charlieamat
Last active September 30, 2021 18:15
Show Gist options
  • Save charlieamat/292dc34d7d7ddaedf41a9115efd5c3af to your computer and use it in GitHub Desktop.
Save charlieamat/292dc34d7d7ddaedf41a9115efd5c3af to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Composition vs Inheritance (2)
  • Remove all references to Achievements from InteractableItem
  • Create InteractableAchievement.cs
    • Let's see if we can lean into inheritance and create a hierarchy that'll help us untangle this code
  • Add an Achievements field called "Achievements"
  • Add a string field called "Identifier"
  • Add a call to Achievements.Track(Identifier) to Interact()
  • Make InteractableItem inherit InteractableAchievement
    • Okay, that's much better
    • We've decoupled our code so that items and achievements don't have to know about each other
    • But what happens if we need to notify another system?
      • Let's pretend that we have to notify some sort of an item respawn system
      • Do we keep building this hierarchy?
      • If so, what order should the hierarchy be in?
public abstract class Interactable : MonoBehaviour
{
public abstract void Interact();
}
public class InteractableAchievement : Interactable
{
public Achievements Achievements;
public string Identifier;
public void Interact()
{
Achievements.Track(Identifier);
}
}
public class InteractableItem : InteractableAchievement
{
public Inventory Inventory;
public string Item;
public void Interact()
{
Inventory.Add(Item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment