[UE4]代理事件(C++)

用宏定义类似格式:

DECLARE_DELEGATE   //普通代理
DECLARE_DYNAMIC_DELEGATE_TwoParams //动态代理
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams //动态多广播代理 //多出的两个关键字的作用
In the case of multicast delegates,
any number of entities within your code base can respond to the same event and receive the inputs and use them. In the case of dynamic delegates,
the delegate can be saved/loaded within a Blueprint graph (they're called Events/Event Dispatcher in BP).

DYNAMIC:可以在蓝图里被序列化后定义和绑定操作。

MULTICAST:可实现一个事件类型多函数广播(事件类型必须声明为蓝图类型)

XXXParams:(使用DYNAMIC时)参数个数,宏定义参数里一个参数类型对应一个参数名字。

//声明位置(巩固下C++基础)

如果用到了静态事件类型的变量,因为需要在类外部声明这个变量,所以宏定义代理需要放在类外部。否则,随便放哪都行(在使用之前)。

注意:

1.当使用MULTICAST时,声明的代理事件类型需要声明为蓝图类型。不然报错,如:

//声明代理
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FLoadDesignsDelegateEvent, const TArray<FDesignInfo>&,
_designsInfo, const bool, _result); //声明代理事件类型
static FLoadDesignsDelegateEvent m_OnLoadDesignsEve; //调用代理事件
UFUNCTION(BlueprintCallable, Category = "BZone|SaveGameSystem")
static
void GetOneDesignFromServer(const FString &_userId, const FString& _desingId,const FLoadDesignDelegateEvent& _eve); //报错
F:/UE4_Projects/CGroupSystem_Server/Plugins/SaveGamePlugin/Source/SaveGamePlugin/SaveGame/Public/SaveGameBPLibrary.h()
: Type '{multicast delegate type}' is not supported by blueprint. Function: GetAllDesignsFromServer Parameter _event

2.调用时先检查下是否绑定了代理

RamaMeleeWeapon_OnHit.IsBound() 

新版本的:m_DelegateEvent.ExecuteIfBound(params...);

3.UObject和C++的不同绑定

不是MULTICAST:

//UObject
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.BindUObject(this,&USomeClass::RespondToMeleeDamageTaken);
//C++
RamaMeleeWeaponComp->RamaMeleeWeapon_OnHit.BindRaw(this,&FSomeRawCPPClass::RespondToMeleeDamageTaken);

是MULTICAST:

TScriptDelegate<> t_de1;

t_de1.BindUFunction(this, STATIC_FUNCTION_FNAME(TEXT("ADrawHouseManager::Mouse_LeftOneClick")));

m_leftOneClickEvents.Add(t_de1);

并且Mouse_LeftOneClickDown();需要UFUNCTION()修饰,否则事件可以添加进代理,但不会进入函数(不在UE的函数列表里所以无法找到并执行)。

封装后的:

TMap<TMulticastScriptDelegate<>*, TScriptDelegate<>> m_bindEvents;

void ADrawHouseManager::AddBindEvent(TMulticastScriptDelegate<>* const _dele, const FString& _functionName)
{
if (_dele!=nullptr&&!_functionName.IsEmpty())
{
TScriptDelegate<> t_de;
FString t_str = "ADrawHouseManager::" + _functionName;
t_de.BindUFunction(this, STATIC_FUNCTION_FNAME(*t_str));
_dele->Add(t_de);
m_bindEvents.Add(_dele, t_de);
}
}

别忘记对象销毁时在析构函数里调用解绑!!!

void ADrawHouseManager::UnBindAllInputEventsFromPC()
{
if (m_bindEvents.Num()>)
{
for (auto it:m_bindEvents)
{
TMulticastScriptDelegate<>* t_dele = it.Key;
if (t_dele!=nullptr)
{
t_dele->Remove(it.Value);
}
}
}
}
ADrawHouseManager::~ADrawHouseManager()
{
UnBindAllInputEventsFromPC();
}

其余细节见:

https://wiki.unrealengine.com/Delegates_In_UE4,_Raw_Cpp_and_BP_Exposed  //C++代理事件

https://docs.unrealengine.com/latest/CHN/Programming/UnrealArchitecture/Delegates/index.html

上一篇:关于开启.NET在线提升教育培训的通知! - 可在此页面观看在线直播!


下一篇:C#:Func的同步、异步调用