Why do we enable our input system movement in an ‘OnEnable’ method instead of in an ‘Awake’ method? Given the order of execution info, doing it in either type of method would work, right? Or is there a subtle difference I’m failing to appreciate?
Hi,
Awake gets called only once: when the object gets created. Since we disable the input system in OnDisable, we would never be able to enable it again if we enabled it in Awake. OnEnable gets called whenever “this” component becomes active.
Did this make sense?
See also:
- Forum User Guides : How to mark a topic as solved
Yes, that makes sense - thank you very much
One follow up question, if that’s OK…
Why are we Disabling the Input System at all? Rick said something about adding OnDisable() to ‘clean up’ the code, but I wasn’t sure exactly of the necessity behind doing this. Is it relating to performance? (i.e. if we didn’t disable the Input System, would it slow down our game?)
Many thanks
Yes, one reason is the performance. We don’t want to have our method being called in an event if we disable the game object. Each executed command requires computing capacity.
The second reason is an unwanted behaviour. In C#, an object exists or it does not exist. There is no state like “enabled” or “disabled”. For this reason, C# event handlers always call all methods that are assigned to it whenever the event handler gets invoked. It does not distinguish between methods on enabled/disabled game objects in Unity.
The third reason are potential memory leaks. In C#, the garbage collector destroys all objects that are not in use anymore. For this reason, we do not have to worry about deallocating space in memory, which is great. However, the requirements of “in use” are fairly low. Being referenced somewhere is sufficient for “being in use”. Being referenced could mean that the object was added to a List at some point and is still in that List. In the worst case, you cannot find the concerning object again because it is “buried” somewhere. And if you have thousands of these “orphaned” objects, you will eventually notice that you have less and less free space in memory. Your game could freeze.
To prevent these memory leaks, we remove references manually.
Also see the answers in this thread. The programming language is not C# but the concept and the reasons are the same.
Thanks so much for taking the time to give such a detailed response: it’s appreciated.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.