I have a number of assets that I imported for various “items” in my game. I have converted each asset into a Sprite.
In C++, I have subclassed a class ASLBaseSpriteActor
from APaperSpriteActor
, so that I can dynamically spawn various “items” in the world.
I’m struggling with dynamically setting which particular sprite should be used for a new spawned ASLBaseSpriteActor
.
If I put this into the constructor:
ASLBaseSpriteActor::ASLBaseSpriteActor() {
UE_LOG(LogTemp, Warning, TEXT("ASLBaseSpriteActor::constructor"));
UPaperSprite* sprite = Cast<UPaperSprite>(StaticLoadObject(UPaperSprite::StaticClass(), NULL, TEXT("/Script/Paper2D.PaperSprite'/Game/Assets/Items/apple_Sprite.apple_Sprite'")));
UE_LOG(LogTemp, Warning, TEXT("ASLBaseSpriteActor::Initialize2"));
if (sprite) {
UE_LOG(LogTemp, Warning, TEXT("ASLBaseSpriteActor::Initialize got sptire"));
UPaperSpriteComponent* renderComponent = this->GetRenderComponent();
if (renderComponent) {
this->GetRenderComponent()->SetSprite(sprite);
UE_LOG(LogTemp, Warning, TEXT("ASLBaseSpriteActor::Initialize got render comp"));
}
}
}
It works fine - I can see the “apple” item in the world upon spawning the APaperSpriteActor
. The problem is that eventually, the path to the sprite will need to be a parameter. But, if I put the same block of code say into BeginPlay
, I cannot see the item anymore in the world, although, based on my logs, all references to sprite
and renderComponent
are not null.
I have tried deferred spawning as well - from my game mode, I do:
void ASLGameModeBase::BeginPlay() {
UWorld* const World = GetWorld();
if (World) {
const FTransform SpawnLocAndRotation;
ASLBaseSpriteActor* newItem = World->SpawnActorDeferred<ASLBaseSpriteActor>(ASLBaseSpriteActor::StaticClass(), SpawnLocAndRotation);
newItem->Initialize();
newItem->FinishSpawning(SpawnLocAndRotation);
}
}
I tried putting the code from the APaperSpriteActor
into the APaperSpriteActor::Initialize
but that doesn’t work either.
I am out of ideas, aside from subclassing APaperSpriteActor
for each of my items to just set the path to the sprite in the constructor. How can I achieve what I want with just a single APaperSpriteActor
class that can dynamically attach a sprite to its instance when spawned in the world, based on a path parameter?