Skip to content

Instantly share code, notes, and snippets.

@charlieamat
Last active September 30, 2021 18:12
Show Gist options
  • Save charlieamat/d5533060a6792d78523054cda52e2292 to your computer and use it in GitHub Desktop.
Save charlieamat/d5533060a6792d78523054cda52e2292 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Composition vs Inheritance (1)
  • Convert Interactable.cs into an abstract class
  • Convert Interact() into an abstract method
    • Taking the inheritance approach, our plan will be to have each new interactable inherit from Interactable
  • Create InteractableItem.cs
  • Make InteractableItem inherit from Interactable
  • Implment Interact()
    • If we want the player to be able to interact with items, we need to create a new implementation of Interactable to handle it
  • Add a string property called "Item"
  • Add an Inventory property called "Inventory"
  • Add a call to Inventory.Add(Item) to Interact()
    • We'll keep our initial implementation simple
    • No spaghetti code here, right?
    • But what if we want to reward the player with an achievement when they collect a certain amount of a particular item?
  • Add an Achievements field called "Achievements"
  • Add a string property called "AchievementIdentifier"
  • Add a call to Achievements.Track(AchievementIdentifier)
    • Here's where we run into our first bit of trouble
    • We've just coupled our achievement system to interactable items
    • This may seem small and isolated, but it's likely that other systems or behaviors will eventually need to know when an item has been interacted with
public class Achievements : MonoBehaviour
{
public void Track(string identifier)
{
// Track achievememnt progress
}
}
public abstract class Interactable : MonoBehaviour
{
public abstract void Interact();
}
public class InteractableItem : Interactable
{
public Inventory Inventory;
public string Item;
public Achievements Achievements;
public string AchievementIdenifier;
public void Interact()
{
Inventory.Add(Item);
Achievements.Track(AchievementIdenifier);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment