Constructor called twice


#1

I am spawning a pawn in a world, and I noticed that its constructor is being called twice: Once when I declare and bind it in SK, and the other when I ‘spawn’ it in the game world.

I am wanting to override the BP defaults with custom settings, but I cannot touch these them when the constructor is first called since these references are null (I presume because it hasn’t spawned in the game world, UE4 hasn’t initialized the object’s memory). Having to “wait” until the second constructor call is too late, since I want these defaults overriding UE4’s, and by this point the object is now created.

I feel as though I am playing with fire here. Any suggestions?


#2

You do need to be careful with what you do in the constructor. Because there isn’t any guarantee as to when it fires, it could be the actor coming into the world for the first time, it could be a temporary object being created.

If you’re trying to make sure certain variables are set before BeginPlay fires on the actor then usually the pattern you would use is to deferred spawn an actor, set variables and then finish spawning.

e.g.

!c : GameLib.begin_deferred_actor_spawn_from_class(,some_class, some_transform, ESpawnActorCollisionHandlingMethod.@@adjust_if_possible_but_always_spawn)
c.@some_var := 1
c : GameLib.finish_spawning_actor(c, some_transform)

#3

Thanks!

Am I safe to call begin / finish spawning in the constructor? Or would you recommend that I separate that out into its own method?


#4

Generally no since the game world might not exist yet. It would be better to do this on BeginPlay.


#5

Thanks. I’m trying to use on_begin_play, which tells me via comment to override the method in my subclass, but I’m not seeing any documentation on how to do that. How does that work?


#6

This isn’t wired. So you’ll actually need to call some custom &blueprint annotated function from the blueprint’s BeginPlay.


#7

I see. Thanks!