Is "ObjectInitializer" still in use?

I have learned to work by adding an ObjectInitializer by reference in all my classes, then in the constructor I use CreateDefaultSubObject and that to add things. Is that a good practice? I’ve learned it from old tutorials.

And a noob question, who creates the instances of my classes? When I add to the signature of my class constructor definition a: Super (ObjectInitializer) who is creating and finally passing that ObjectInitializer?



ABackground::ABackground(const FObjectInitializer& ObjectInitializer):Super(ObjectInitializer)
{
.
.
.
.
}

ABackground is inherited from AActor, when you do Super (ObjectInitializer) you pass the ObjectInitializer to the constructor of the base class, right? But where does the ObjectInitializer finally come from, instantiated in memory? Who creates it and introduces it to the creation of my ABackground?

I have instantiated Pawns and Actors and I have not introduced any ObjectInitializer. Still I use it effectively in the constructor of that Pawns and Actors. I’ve done it through World, SpawnActor and StaticClass() function. It’s okay?


Sprite = ObjectInitializer.CreateDefaultSubobject<UPaperSpriteComponent>( this, TEXT( "SpriteComp" ) );

I still need work to see everything well, complete, from a distance.

PD:
I have also observed in the tutorials that I have seen that working in 2D applies movement on the Sprite, and not on the position of the actor, is that correct? Is it my own choice?

  1. You don’t need ObjectInitializer anymore (definitely since 4.22, probably much earlier even). It’s a legacy struct, and it’s functionality was moved directly to UObject. That’s why you can call CreateDefaultSubobject in a UObject constructor even without referencing the ObjectInitializer. You will probably continue to see it in tutorials, etc. until everyone hears the good news (and even after, because old habits die hard).

  2. Dig into the NewObject<T>() function. You’re supposed to use this to create new objects at runtime, and it has tons going on in the background. Somewhere in the depths of that function, you should find where ObjectInitializer is supplied to the constructor.

  3. It’s your choice whether to move the Sprite component or the containing actor. I would suggest actor in most cases, but I guess it’s context dependent (like maybe you have many Sprites on one actor).

3 Likes