Casting an Iterator

Hi,

I run with an Iterator over all available classes and then want to do something when the class is a subclass of a specific class.
While I can find the needed classes, I can’t cast them to the the required class I need to access some static variables I need.

The code:

for (TObjectIterator<UClass> It; It; ++It)
    {
        if(It->IsChildOf(UMagicEffect::StaticClass()))
        {
            UE_LOG(LogTemp, Warning, TEXT("Class: %s"), *(It->GetFName().GetPlainNameString()));
            UMagicEffect* pTmpMagicEffect = Cast<UMagicEffect>(*It);
            if (pTmpMagicEffect != nullptr)
            {
                UE_LOG(LogTemp, Warning, TEXT("Works"));
            } 
            else
            {
                UE_LOG(LogTemp, Warning, TEXT("nullptr"));
            }
        }
    }

The first UE_LOG triggers but the second one always returns “nullptr”.

Has someone an Idea how to get this Cast to work?

It will never succeed because the UClass itself isn’t a MagicEffect. It’s the type information about the class that derives from MagicEffect.

The good news is you can get at an instance of the class by calling GetDefaultObject on the class. I’m not sure if you can get at static data that way, but you can sure try.

This is not how you should use object iterators. You can pass the class you’re looking for in between the template brackets, like so:

for (TObjectIterator<UMagicEffect> It; It; ++It)
{
    It->DoTheThing();
}

You might want to check if the object is pending kill since I think those also get returned by object iterators (actor iterators are safe from this).

Also don’t forget to check what world the object is in. If you have any of these objects placed in the level (subobjects or components) Object Iterator will pick up object both in the level and in your PIE session.

Thanks for the replies.
I also got the idea to instance the class and use that while my post was pending for approvement (posted this question last week). This works so far.

I tried to use

TObjectIterator<UMagicEffect> 

but got no results. I’ll revisit this in the future and try it again when everything else around this works. Maybe I had some other error that gave me an empty result…