Novemeber 4, 2019
Beginner Programming: Unity Game Dev Courses
Beginner Programming: Unity Game Dev Courses
Unity Learn Course – Beginner Programming
Handling Events
The Demo Project
This section focused on handling inter-object communications. They covered direct object calls, tight coupling, and loose coupling. This topic was covered using mostly delegates and events.
Events: something that happens within the context of one object to be communicated to other
The first objective of the tutorial was to restric the rate of fire of the player ship so that it could only have one projectile on the screen at any time. They could not fire again until that projectile was destroyed (which in this case, only occurred once it left the screen).
Direct Object Calls
Direct Object Calls: directly make a call from within one object to a method in another object (usually through public methods)
Example: The ship needed to be able to fire again when the projectile reached the end of the screen. The projectile used a reference to the PlayerController to call a method within it when the projectile reached the end of the screen to reenable the firing mechanism.
Costs: This forces you to expose a lot of methods within objects so that others may access them.
Tight Coupling
Tight Coupling: making objects dependent on one another; can be done by having one object call a method found in another object
Costs:
- Difficult to maintain and debug
- Not easily scalable
- Impedes collaboration (like Git or Collab)
- Complicates Unit Testing
Delegates and Events
This section looks to use delegates and events to get around the issues found with direct object calls and tight coupling. These allow for loose coupling.
Important Notes
- One way to think of delegates is that they are method variables.
- All events have an underlying delegate type.
Example: The ProjectileController script created a public delegate and public event. It then called that event within its code somewhere (which would then execute any methods assigned to that event). The PlayerController assigned one of its methods to that public event when instantiating the projectile. The ProjectileController could then effectively call that PlayerController method by calling the event within it.
SUMMARY
Delegates and events can provide a nice way to create loose coupling, which can lead to better and easier to maintain ways to allow your objects to communicate between one another. Be careful with direct object calls and tight coupling as they can reduce encapsulation and lead to tricky debugging problems down the road.