ue4-动态代理

  • c++ and bp 混合使用动态代理
  • 及各种bind

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

  1. c++中定义一个动态代理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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;
    };
  2. 在蓝图中绑定这个代理
    这里写图片描述

  3. 起个LibFunc静态方法测试,在c++广播这个代理

    1
    2
    3
    4
    void UMyBpFuncLib::TestBpDelegate(AMyChar * _myChar, int32 _num)
    {
    _myChar->OnMyDelegate2.Broadcast(_num);
    }
  4. 蓝图中调用这个测试方法
    这里写图片描述

  5. 结果
    这里写图片描述


代理的各种bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//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);
  • 蓝图中的方法
    这里写图片描述

参考资料