- 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
inInteract()
- 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
usingGetComponents<InteractionHandler>()
inStart()
- Switch to Unity
- Update the Scene and verify the behavior
Last active
September 30, 2021 19:00
-
-
Save charlieamat/5d2c501586b5a864efd0c9b12f5f2fe7 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Composition vs Inheritance (3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InteractableAchievement : InteractionHandler | |
{ | |
public Achievements Achievements; | |
public string Identifier; | |
public void Interact() | |
{ | |
Achievements.Track(Identifier); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InteractableItem : InteractionHandler | |
{ | |
public Inventory Inventory; | |
public string Item; | |
public void Interact() | |
{ | |
Inventory.Add(Item); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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