How to use FindObject() in C++ to find an Object in memory/world that has been constructed using NewObject() in C++?

I have used the following code to construct an Object Class into the memory:

void UAbilitySystemComponent::add_ability(TSubclassOf<UABILITY> ability_class)
{
    UABILITY* ability = NewObject<UABILITY>(GetTransientPackage(), ability_class);
    if (ability)
    {
        UE_LOG(LogTemp, Warning, TEXT("Ability added - %s"), *ability->GetName());
    }
    else
    {
        UE_LOG(LogTemp, Warning, TEXT("Failed to create ability - %s"), *(ability_class->GetName()));
    }
}

The above code uses GetTransientPackage() for Outer parameter and ability_class name. The Object is also being constructed.

I am using the following code to get the Object in memory:

UABILITY* UAbilitySystemComponent::get_ability(TSubclassOf<UABILITY> ability_class)
{
    UABILITY* ability = Cast<UABILITY>(FindObject<UObject>(GetTransientPackage(), *(ability_class->GetName())));
    if (ability)
    {
        UE_LOG(LogTemp, Warning, TEXT("Found ability - %s"), *ability->GetName());
    }
    else
    {
        UE_LOG(LogTemp, Warning, TEXT("Could not find ability - %s"), *(ability_class->GetName()));
    }

    return ability;
}

Although here, I am unable to find the ability. I get the Log Message -

"Could not find ability - <ability-name>"

I have also tried using GetWorld() for Outer parameter for adding NewObject and finding object. Yet it doesn’t work!

Please help me with this. Where am I going wrong?
Something wrong with the class-name or Outer parameter?

Thanks in advance.

You need to pass in the exact name that is in the world
if the spawned class name is the world (as in the outliner) is “AbilityA_C_0”
then you should call

UAbility* ability = FindObject<UAbility>(GetTransientPackage(), TEXT("AbilityA_C_0"));

Hard-coded test shows that you need the direct name

1 Like

Yes, adding the right class name as the name of the Object solved the issue.

I have implemented like this:

UABILITY* Uability_system_component::get_ability(TSubclassOf<UABILITY> ability_class)
{
	UABILITY* ability = Cast<UABILITY>(FindObject<UObject>(
		GetWorld()->GetCurrentLevel(),		// context/Outer-Object where to find object
		*(ability_class->GetName())			// path name of object w.r.t context
	));

    if(!ability) return nullptr;
    return ability;
}


void Uability_system_component::RPC_add_ability_Implementation(TSubclassOf<UABILITY> ability_class)
{
		ability = NewObject<UABILITY>(
			GetWorld()->GetCurrentLevel(),
			ability_class,
			ability_class->GetFName(),
			RF_Standalone
		);
                
        // ...

}

Thanks!

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