UE4/CPP C++绑定UMG中的按钮事件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/I_itaiit/article/details/80344864
  • 创建Widget Blueprint蓝图,命名为MainMenu;
  • 创建继承于Uesr Widget类的c++类,命名为MainUserWidget,设置MainMenu的父类为MainUserWidget
    这里写图片描述
  • 在MainMenu蓝图中拖入两个按钮分别命名为:StartGameBtn和QuitGameBtn;
  • 在c++类MainUserWidget.h文件中定义与按钮对应的属性:
public:
    UPROPERTY(Meta = (BindWidget))
        UButton* StartGameBtn;
    UPROPERTY(Meta = (BindWidget))
        UButton* QuitGameBtn;

属性的名字与按钮的名字对应。定义两个方法:

    UFUNCTION()
        void StartGame();
    UFUNCTION()
        void QuitGame();
  • 获得MainMenu中按钮的引用并赋值给类中的属性,并且绑定事件
    if (UButton* SBtn = Cast<UButton>(GetWidgetFromName("StartGameBtn")))
    {
        StartGameBtn = SBtn;
        UE_LOG(LogTemp, Warning, TEXT("StartGameBtn"));

        FScriptDelegate sgbDelegate;
        sgbDelegate.BindUFunction(this, "StartGame");
        StartGameBtn->OnReleased.Add(sgbDelegate);
    }

参考的文章,感谢作者的分享和对我的帮助:

  1. UE4C++获得UMG控件:https://blog.csdn.net/l171672538/article/details/78873264,但里面的绑定事件的方法在新版本的UE引擎中(我目前使用的是4.19.2)无法使用。

  2. [UE4]退出游戏的API(C++):http://aigo.iteye.com/blog/2291979,相当于蓝图中的Quit Game节点。里面的内容为以下代码:

    1. #include "KismetSystemLibrary.h"  
    2.   
    3. void ASomeActor::SomeActorFunction()  
    4. {  
    5.     UKismetSystemLibrary::QuitGame(this, nullptr, EQuitPreference::Quit);  // 主要调用的方法
    6. }  
  1. http://aigo.iteye.com/blog/2296218,这里面讲了创建一个与UMG蓝图相关联的类的方法。

  2. https://blog.csdn.net/zilisen/article/details/77645500,在这篇文章中找到了在新版本引擎中绑定按钮点击事件的方法:即使用FScriptDelegate

猜你喜欢

转载自blog.csdn.net/I_itaiit/article/details/80344864
今日推荐