c++ and bp 混合使用动态代理

270 阅读1分钟
  1. c++中定义一个动态代理

DECLARE_DELEGATE_OneParam(FMyDelegate1, int32);
//c++和bp混合使用的代理必须是这种宏,而不是上面那种
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FMyDelegate2, int32, abc);

UCLASS()
class AMyChar : public ACharacter
{
    GENERATED_BODY()
public:
    //必须声明为BlueprintAssignable,只给蓝图绑定这个代理
    UPROPERTY(BlueprintAssignable, Category = "MyChar")
        FMyDelegate2 OnMyDelegate2;
};
————————————————
版权声明:本文为CSDN博主「蝶泳奈何桥.」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yangxuan0261/article/details/52097699

2.在蓝图中绑定这个代理 image.png

  1. 起个LibFunc静态方法测试,在c++广播这个代理
void UMyBpFuncLib::TestBpDelegate(AMyChar * _myChar, int32 _num)
{
    _myChar->OnMyDelegate2.Broadcast(_num);
}
  1. 蓝图中测试

image.png

各种绑定

//declare
DECLARE_DELEGATE_OneParam(FMyDlg1, int32); //为multi服务

//共享指针中的方法
class Test : public TShareFromThis<Test>
{ 
public:
    void Output(int32 num) {
        UE_LOG(LogMyTest, Warning, TEXT("--- TSharePtr, num:%d"), num);
    }
};

//静态方法
static void gOutput(int32 num) {
    UE_LOG(LogMyTest, Warning, TEXT("--- static method, num:%d"), num);
}

//Lambda表达式
auto lambdaFunc [&](int32 num)->void {
    UE_LOG(LogMyTest, Warning, TEXT("--- lambdaFunc, num:%d"), num);
}

//Uobject的方法
void AMytest::Log(int32 num) {
    UE_LOG(LogMyTest, Warning, TEXT("--- AMytest::Log, num:%d"), num);
}

//蓝图中的方法
//贴到这段代码的下面了

FMyDlg1 mDlg1;
FMyDlg1 mDlg2;
FMyDlg1 mDlg3;
FMyDlg1 mDlg4;
FMyDlg1 mDlg5;
TSharePtr<Test> mTestPtr = TSharePtr<Test>(new Test); //new一个共享指针


//bind
mDlg1.BindUObject(this, &AMytest::Log); //this只能是继承自UObject的类
mDlg2.BindSP(mTestPtr.Get(), &Test::Output) //继承自TShareFromThis<XXX>的类
mDlg3.BindStatic(&gOutput); //静态方法
mDlg4.BindLambda(lambdaFunc); //lambda表达式
mDlg5.BindUFunction(this, "testDelegateUFunctionBp"); //this的蓝图中的方法

//execut
mDlg1.Execute(111);
bool b2 = mDlg2.ExecuteIfBound(222);
bool b3 = mDlg3.ExecuteIfBound(222);
bool b4 = mDlg4.ExecuteIfBound(222);
bool b5 = mDlg5.ExecuteIfBound(222);

image.png