# UGameInstance里直接调用
获取到引用了,就可以自然的调用。忽略
# UGameInstance里间接调用,通过代理调用
- 前置已经添加了websocket,具体步骤参考,链接
- 在UWebSocketGameInstance.h里新增代理,并在链接成功后进行绑定。
#pragma once #include "myue521Character.h" #include "CoreMinimal.h" #include "Engine/GameInstance.h" #include "WebSockets/Public/IWebSocket.h" #include "UWebSocketGameInstance.generated.h" DECLARE_DELEGATE_OneParam(JSONMessageTrigger, FString) /** * */ UCLASS() class MYUE521_API UUWebSocketGameInstance : public UGameInstance { GENERATED_BODY() public: JSONMessageTrigger JSONMessageTrigger; public: virtual void Init() override; virtual void Shutdown() override; TSharedPtr<IWebSocket> WebSocket; void OnConnected(); void OnConnectionError(const FString& Error); void OnClosed(int32 StatusCode, const FString& Reason, bool bWasClean); void OnMessage(const FString& Message); // 接收消息时 void OnMessageSent(const FString& MessageString); // 发送消息时 private: Amyue521Character* myCharacher; public: Amyue521Character* getMyCharacher(); };
说明,
-
声明一个代理。DECLARE_DELEGATE_OneParam(JSONMessageTrigger, FString)
-
声明触发器。public:
JSONMessageTrigger JSONMessageTrigger; -
下面到实现类里进行绑定,我这里是在UWebSocketGameInstance.cpp里,socket链接成功后进行绑定。
-
- 绑定,并调用。这里尝试着获取到目标characher.
Amyue521Character* UUWebSocketGameInstance::getMyCharacher() { if (this->myCharacher != nullptr) { return this->myCharacher; } //获取player,并转化为Amyue521Character ACharacter* character = UGameplayStatics::GetPlayerCharacter(this->GetWorld(), 0); this->myCharacher = Cast<Amyue521Character>(character); if (this->myCharacher != nullptr) { //转化成功后则进行绑定 JSONMessageTrigger.BindUObject(this->myCharacher, &Amyue521Character::CallBackFunMul); //模拟触发,这个触发实际应该放到收到message方法里执行 FString TestHUDString = FString(TEXT("my json msg")); JSONMessageTrigger.ExecuteIfBound(TestHUDString); } return this->myCharacher; } void UUWebSocketGameInstance::OnConnected() { UE_LOG(LogTemp, Warning, TEXT("%s"), *FString(__FUNCTION__)); GEngine->AddOnScreenDebugMessage(-1, 3.0f, FColor::Green, "Successfully Connected"); this->getMyCharacher(); }
说明:
-
这里进行了代码简化,链接成功后将获取的player转化为目标Characher
ACharacter* character = UGameplayStatics::GetPlayerCharacter(this->GetWorld(), 0); this->myCharacher = Cast<Amyue521Character>(character);
-
绑定文章来源:https://www.toymoban.com/news/detail-688184.html
if (this->myCharacher != nullptr) { JSONMessageTrigger.BindUObject(this->myCharacher, &Amyue521Character::CallBackFunMul); }
-
触发,这个触发实际应该放到收到OnMessage方法里执行文章来源地址https://www.toymoban.com/news/detail-688184.html
if (this->myCharacher != nullptr) { FString TestHUDString = FString(TEXT("my json msg")); JSONMessageTrigger.ExecuteIfBound(TestHUDString); }
-
到了这里,关于UE5- c++ websocket里实现调用player里的方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!