UObject调用上下文函数(WorldContext,UWor

2024-01-18  本文已影响0人  Moo2077

UObject通常无法调用任何需要传入WorldContext的方法,例如延时函数Delay,TimeLine或者某个SubSystem:

image.png

Delay这种上下文函数根本没办法创建,而Subsystem则会报错

image.png
//蓝图如果定义了这句话则不能在UObject中调用
UFUNCTION(BlueprintCallable, meta=(WorldContext="WorldContextObject")
void ChildFunction(UObject* WorldContextObject)

主要原因

蓝图检测.png

解决方法:
新建UObject子类并重写下列方法

class YOUR_API UChildObject : public UObject
{
    GENERATED_BODY()
public:
        //UObject work flow
    virtual UWorld* GetWorld() const override;
    virtual bool ImplementsGetWorld() const override;
}

.CPP中重写

UWorld* UChildObject ::GetWorld() const
{
    // CDO objects do not have a world.
    // If the object outer is destroyed or unreachable we are likely shutting down and the world should be nullptr.
    
    if (UObject* Outer = GetOuter())
    {
        if (!HasAnyFlags(RF_ClassDefaultObject)
            && !Outer->HasAnyFlags(RF_BeginDestroyed)
            && !Outer->IsUnreachable())
        {
            return Outer->GetWorld();
        }
    }
    UWorld* world = nullptr;//= Super::GetWorld();
    if (UObject* Outer = GetOuter())
    {
        world = Outer->GetWorld();
    }
    if(world == nullptr)
    {
        for(auto context : GEngine->GetWorldContexts())
        {
            if(context.WorldType != EWorldType::Editor || context.WorldType != EWorldType::EditorPreview)
            {
                world = context.World();
            }
        }
    }
    if(world == nullptr)
    {
        world = GEngine->GetWorldContexts()[0].World();
    }
    return world;
}

bool UChildObject ::ImplementsGetWorld() const
{
    return true;
}

在UE编辑器中创建蓝图BlueprintClass并继承上述子类,就会愉快的发现可以调用任何函数了

UE 5.3环境

上一篇 下一篇

猜你喜欢

热点阅读