Search code examples
c++pointersunreal-engine4spawnnullptr

UE4 set Actor pointer to null without destroying it in the world


I'm trying to figure out if it is possible to reset the pointer of an Actor and simultaneously not make it disappear from the world.
Example:
1. auto Item = GetWorld()->SpawnActor<...>(...);
2. ...
3. Item = nullptr;- resetting just the pointer
4. Actor is still in the world
I believe that duplicating this actor would work, but it mustn't be the best solution IMO.


Solution

  • You seem to be working with the assumption that clearing a pointer will automatically destroy the Actor. Have you verified that is actually the case?

    Looking at the docs, SpawnActor just returns a regular 'dumb' pointer. In C++, resetting a plain pointer to null does not destroy the object it references; some explicit action is probably needed, to destroy it. The UE4 article on Actor Lifecycle seems to support this as well.

    This could probably take the form of resetting a smart pointer (TSharedPtr), or calling Destroy on the actor itself.