UE5- c++ websocket里实现调用player里的方法

# UGameInstance里直接调用


获取到引用了,就可以自然的调用。忽略

# UGameInstance里间接调用,通过代理调用


  1. 前置已经添加了websocket,具体步骤参考,链接
  2. 在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 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();
    	
     
    };

    说明,

    1. 声明一个代理。DECLARE_DELEGATE_OneParam(JSONMessageTrigger, FString)

    2. 声明触发器。public:
          JSONMessageTrigger JSONMessageTrigger;

    3. 下面到实现类里进行绑定,我这里是在UWebSocketGameInstance.cpp里,socket链接成功后进行绑定。

  3. 绑定,并调用。这里尝试着获取到目标characher.
    Amyue521Character* UUWebSocketGameInstance::getMyCharacher() {
    	if (this->myCharacher != nullptr) {
    		return this->myCharacher;
    	}
    //获取player,并转化为Amyue521Character
    	ACharacter* character = UGameplayStatics::GetPlayerCharacter(this->GetWorld(), 0);
    	this->myCharacher = Cast(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();
     
    }

    说明:

    1. 这里进行了代码简化,链接成功后将获取的player转化为目标Characher

      ACharacter* character = UGameplayStatics::GetPlayerCharacter(this->GetWorld(), 0);
      this->myCharacher = Cast(character);
    2. 绑定

      if (this->myCharacher != nullptr) {
      	JSONMessageTrigger.BindUObject(this->myCharacher, &Amyue521Character::CallBackFunMul);
      
      }
    3. 触发,这个触发实际应该放到收到OnMessage方法里执行

      if (this->myCharacher != nullptr) { 
      	FString TestHUDString = FString(TEXT("my json msg"));
      	JSONMessageTrigger.ExecuteIfBound(TestHUDString);
      }

你可能感兴趣的:(ue5,c++,websocket)