[C++] Destroying an actor during Tick()


It is possible with my current setup to destroy an actor half way through a component’s TickComponent() function. When I call Destroy(), the actor immediately has all of the appropriate methods called, including EndPlay(). The call stack looks something like this when the actor is being destroyed:

During TickComponent(), it is possible to encounter code that can call Destroy(), which in this case is AKillActorScriptNode::Run(). As is clear by the call stack, EndPlay() is called before AKillActorScriptNode::Run() has finished executing. Since I am using EndPlay() for necessary cleanup, once the call stack returns to TickComponent(), the component is no longer in a valid state and the code fails.

Is there any good way to delay the destruction until the end of the frame, or am I required to perform checks throughout TickComponent() to make sure the actor is still valid? There are only 2 ways I can think of doing this manually:

  1. Use a custom bDestroyActorAfterTick flag (or similar) in the UActorScriptComponent which will take care of calling Destroy() if the flag is true.
  2. Create an actor whose sole job is to destroy other actors during it’s Tick() function. This will ensure actors are always destroyed in an isolated environment while not being used. This is more general and probably a better solution than the first since all calls to Destroy() are simply replaced with adding the actor to be destroyed to this actor.

It would be nice, however, if there is a way to flag an actor for destruction in engine. Is this possible? If not, is there a more elegant way than either of the solutions I listed above to solve the problem?