Assign TSubclassOf in C++ with existing object

this is mostly because this is a GameInstanceSubsystem (hence why I “can not” just assign it in the Editor), but it should be applicable outside of that as well, for say “reassigning a TSubclassOf at runtime without Path/reference string”
when I was trying this with the Path String in the Initialize() I would often get an error where the asset could not be found (probably the asset manager running away with my blueprint even though there are instances of the blueprint in the level :person_shrugging:), and any mutilation of the Path string or Reference string didn’t help.

what I currently have (this can be duplicated with a standard AActor if you don’t want to go through implementing a subsystem and using a Subsystem Browser)

UCLASS()
class [GameAPI] UItemRepo : public UGameInstanceSubsystem
{
   // ...
private:
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = true))
    TSubclassOf<AMyItemPickup> SpawnableItem;
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = true))
    TObjectPtr<AMyItemPickup> FloatingItem;
}
// ...
public:
    UFUNCTION(BlueprintCallable)
    bool RegisterSpawnable(AMyItemPickup* inItem)
    {
        if ( inItem != nullptr && SpawnableItem == nullptr )
        {
            SpawnableItem = inItem->StaticClass();
            FloatingItem = GetWorld()->SpawnActor<AMyItemPickup>(SpawnableItem);
            return true;
        }
        return false;
    }

this function is being called in the BeginPlay() from a blueprint inheriting from AMyItemPickup. using a Subsystem Browser I am able to see the assignment of SpawnableItem is happening, and FloatingItem is being spawned, but SpawnableItem is the C++ class, and FloatingItem is the default blueprint-wrapper of the C++ class.
what I want is the blueprint class to be assigned to SpawnableItem instead of the C++ class.

I guess I just didn’t try enough things…

// "provided"
SpawnableItem = inItem->StaticClass();

// "change to"
SpawnableItem = inItem->GetClass();

it is probably because the inT->StaticClass() will return the UClass of the type as it was last known, and because it hasn’t been cast at that point it is still of type ( in this case AMyItemPickup instead of BPMyItemPickup)
while inT->GetClass() is returning the Class id that the item is regardless of what type the pointer was received as, so technically the signature could have been

// "not great for so many reasons"
bool RegisterSpawnable(UObject* inItem)

though that might have created a debug nightmare in a different way.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.