Download

Creating component in begin play

Hey so I’m using NewObject to create a new sprite component in begin play which comes back as true so I then use spritecomponent->SetSprite to set a sprite but the sprite doesn’t show. When I create the sprite component in the constructor using createdefaultsubobject and SetSprite in begin play, it works perfectly fine and my sprite shows up but I need to create the component in begin play but my sprite isn’t showing up.

Can someone please help me out, thank you! :slight_smile:

Can you post the code?

Sure my bad so for the one that works and shows the sprite:

constructor:

SpriteComponent = CreateDefaultSubobject(TEXT(“SpriteComponent”));

begin play:

SpriteComponent->SetSprite(TestSprite);

For the one that I need to make in begin play but doesn’t work:
begin play:

SpriteComponent = NewObject(this, TEXT(“SpriteComponent”));
SpriteComponent->SetSprite(TestSprite);

Can you also post your declaration of the SpriteComponent variable?

That aside, none of the code you posted should work (including the constructor version). Are you sure you copied it correctly in your post?

Both CreateDefaultObject and NewObject need to be told to use the sprite component class, and I don’t see that in your code.

In the constructor, you should have to use something like
SpriteComponent = CreateDefaultSubobject<UPaperSpriteComponent>("SpriteComponent");

In BeginPlay, it would look more like
SpriteComponent = NewObject<UPaperSpriteComponent>(this, "SpriteComponent"));

1 Like

Hey sorry for the long response but this is the definition in the header:
class UPaperSpriteComponent* SpriteComponent;

And sorry Idk why but it didn’t copy it correctly in the post my bad, it’s how you did it so in the constructor I have:

SpriteComponent = CreateDefaultSubobject<UPaperSpriteComponent>("SpriteComponent");

and in begin play it is:

SpriteComponent = NewObject<UPaperSpriteComponent>(this, TEXT("SpriteComponent"));

But this does work with the constructor but not when I use new object in begin play as it shows correctly here (using a test sprite):

OnPaste.20210807-103045

Thank you again.

When you use NewObject you just create a more or less free-floating object in memory, you still have to do the appropriate setup afterwards. Don’t nail me down on the exact process, but it is something along the lines of:

  SpriteComponent = NewObject...
  Owner->AddInstanceComponent(SpriteComponent);
  SpriteComponent->RegisterComponent();
  Owner->Modify();
  SpriteComponent->AttachToComponent(<CompToAttachTo>,<AttachmentRules>);
1 Like

Thank you so much, this solved my problem!