What is scenario and use cases of OnDestroy() and OnApplicationQuit() functions in unity? When does we use OnDestroy() function and when OnApplicationQuit() function?
As you can imagine by their name, those are functions built to handle executable code only at certain intervals of time in a script's life cycle. Between the two methods, the main difference is when they occur. And I quote from the docs:
OnDestroy occurs when a Scene or game ends. Stopping the Play mode when running from inside the Editor will end the application. As this end happens an OnDestroy will be executed. Also, if a Scene is closed and a new Scene is loaded the OnDestroy call will be made.
While, on the other hands, OnApplicationQuit(), as you can see here, is
Sent to all GameObjects before the application quits.
How and when to use these, it comes by itself, it is quite simple to imagine. In example, think when you want to save or record a score or the status of a player, it wouldn't be my first choice, but, you can save it when the application is about to close, so using OnApplicationQuit(). To use an example for the OnDestroy(), you can imagine having an object enemy and when you call an enemy.Destroy() and you want to assign points to the player. Those are just small examples, but to be sure to understand a script's life cycle, I suggest you to check this page, where you can find the following interesting and complete image, as well as a complete description of that cycle.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With