对《分享一下自己用c++写的小地图》一文的补充

在写完上一篇文章后,发现了一个问题:

那就是编写的插件无法实时预览。

 

在学习了Slate之后,我找到了方法:

重写SynchronizeProperties函数

头文件中添加:

#if WITH_EDITOR
    UFUNCTION()
    virtual void SynchronizeProperties() override;
#endif

因为只需要在编辑器中运行,所以加上了#if WITH_EDITOR

cpp文件中添加:

#if WITH_EDITOR
void UMiniMap::SynchronizeProperties()
{
    Super::SynchronizeProperties();
    WidgetSize = 400;
    MapTextureSize = 512;
    //构建组件
    MainMap = NewObject<UImage>(this, TEXT("MainMap"));
    PlayerCursor = NewObject<UImage>(this, TEXT("PlayerCursor"));
    Frame = NewObject<UImage>(this, TEXT("Frame"));
    //往Widget容器中加入组件
    RootPanel = Cast<UCanvasPanel>(WidgetTree->RootWidget);
    if (RootPanel)
    {
        RootPanel->AddChild(MainMap);
        RootPanel->AddChild(PlayerCursor);
        RootPanel->AddChild(Frame);
    }
    UMaterialInstance *MainMapMaterialInstance = LoadObject<UMaterialInstance>(NULL, TEXT("/Game/UI/Images/MiniMapMaterial_Instance"), NULL, LOAD_None, NULL);
    if (MainMapMaterialInstance)
    {
        MainMapMaterial = UKismetMaterialLibrary::CreateDynamicMaterialInstance(GetWorld(), MainMapMaterialInstance);
        if (MainMapMaterial->Parent->GetMaterial()->MaterialDomain == MD_UI)
        {
            UWidgetLayoutLibrary::SlotAsCanvasSlot(MainMap)->SetSize(FVector2D(WidgetSize, WidgetSize));
            MainMap->SetBrushFromMaterial(MainMapMaterial);
            MainMapMaterial->SetScalarParameterValue(FName(TEXT("MiniMapScaleRatio")), (float)WidgetSize / MapTextureSize);
        }
    }
    UTexture2D* PlayerCursorTexture = LoadObject<UTexture2D>(NULL, TEXT("/Game/UI/Images/PlayerCursor"), NULL, LOAD_None, NULL);
    if (PlayerCursorTexture)
    {
        UWidgetLayoutLibrary::SlotAsCanvasSlot(PlayerCursor)->SetSize(FVector2D(PlayerCursorTexture->GetSizeX(), PlayerCursorTexture->GetSizeY()));
        PlayerCursorSize = PlayerCursorTexture->GetSizeX();
        UWidgetLayoutLibrary::SlotAsCanvasSlot(PlayerCursor)->SetPosition(FVector2D(-PlayerCursorSize / 2 + WidgetSize / 2, -PlayerCursorSize / 2 + WidgetSize / 2));
        PlayerCursor->SetBrushFromTexture(PlayerCursorTexture);
    }
    if (SetImageBurshFromMaterial(TEXT("/Game/UI/Images/FrameMaterial"), Frame, FVector2D(WidgetSize, WidgetSize)))
    {
        UWidgetLayoutLibrary::SlotAsCanvasSlot(Frame)->SetSize(FVector2D(WidgetSize, WidgetSize));
    }
    //后面可以考虑加入别的按钮以及边框
}
#endif

 

不过这样还有有一点小问题,在新建的蓝图(继承这个类的蓝图)中狂点,引擎会直接崩掉,目前找不到解决方案,引擎里都是用Slate的,论坛和AnswerHUB也都没有相关资料,不过这个问题不影响使用,所以教程到此为止了。

posted @ 2016-08-27 18:14  湛蓝玫瑰  阅读(1918)  评论(0编辑  收藏  举报