We just put the OnDestroy code on the UnitSelectedVisual, but should we be putting this code in more places as well? For example, in the future if a second unit dies, will the first unit still be subscribed to the OnDead event? I guess I’m curious if it’s a best practice to always include an OnDestroy + unsubscribe for every event you subscribe to? Thanks!
It all depends on the lifetime of the objects. If both publisher and subscriber have the same lifetime, if they both get destroyed at the same time, then you don’t need to manually handle unsubscribing.
The issue happens when the listener dies but the publisher lives on and keeps on firing events.
The UnitSelectedVisual is listening to the UnitActionSystem, when the unit dies the UnitSelectedVisual dies alongside it but the UnitActionSystem persists, that is why in this case it needs to unsubscribe.
So personally I think about the lifetime of objects and only unsubscribe when I need to.
But if you want to make it a habit of always unsubscribing then that’s also a good habit to have, there’s no harm in unsubscribing even if you don’t specifically need it.
Thanks, that makes sense!
That brings me to another question. I feel like knowing the lifetime of various objects requires a pretty thorough understanding of how you want the code to work while making it. I’ve been doing most things fairly proto-typish/fly by the seat of my pants, so I just hammer away at things until they work.
When you’re trying to write nice code, how much time do you spend preplanning/thinking about how you want to implement a feature/function before you actually sit down and start coding it? Is it something you get better at doing on the fly or is there always some sort of ‘drawing board’ process that comes along with it?
That really depends on exactly what you’re building. Some systems are complex and require quite a bit of thinking beforehand, others are simple and you can just start writing.
For example, working on my next Steam game which is based on this course, for making the Item Transport system it required quite a lot of thinking on exactly what classes I needed, what they would do, etc.
Whereas for something like the Inventory system, it’s something simple I’ve done many times so that didn’t require much pre-planning. Adding 12 Mechanics to my Steam Game in 2 WEEKS! (Devlog 01 - Total World Liberation) - Code Monkey
And yup that is also something that comes from experience.
But also remember what you see in the course is the final polished video, when I’m working by myself I absolutely get NullRefs every once in a while, but because I already have quite a lot of experience when that happens usually I know right away that I just forgot to unsub or do something else.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.