Daily Unreal Column #56 - Actor End Play
It is often the case that we want to execute custom logic when actor is being destroyed. Most often people use OnDestroyed blueprint event or Destroyed native function. But is this the best solution?
In my opinion, it is not. Reason for it not being ideal is that these events are not being called when an actor is being destroyed during level change or when PIE ends.
The better alternative to these two forementioned functions is EndPlay function. This function contains one parameter which is an enumerator defining the reason for this actor being removed from the game.
Here are possible reasons:
/** When the Actor or Component is explicitly destroyed. */
Destroyed,
/** When the world is being unloaded for a level transition. */
LevelTransition,
/** When the world is being unloaded because PIE is ending. */
EndPlayInEditor,
/** When the level it is a member of is streamed out. */
RemovedFromWorld,
/** When the application is being exited. */
Quit,
As you can see, explicit destroy method called by a user is not the only reason actor can be destroyed.
A good reason why you you should always, and especially with With World Partition maps, pair any initialization code from BeginPlay with cleanup in EndPlay is because WP maps turn off s.ForceGCAfterLevelStreamedOut, meaning that levels can be made invisible (all actors call EndPlay) and then made visible again (all actors call BeginPlay) multiple times before actors actually get garbage collected and OnDestroyed gets called.
That means that actor lifecycles are:
Construction -> BeginPlay -> EndPlay -> N * (BeginPlay -> EndPlay ) -> OnDestroyed.
A call to BeginPlay will always be paired with an EndPlay call. Construction and Destruction only happen once each.