Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

- Blueprint Sample

- Code Sample

...

SpaceListWidget.h:

Code Block
#pragma once

#include "CoreMinimal.h"
#include "Types/CavrnusCallbackTypes.h"
#include "Blueprint/UserWidget.h"
#incldue "SpaceWidget.h"
#include "SpaceListWidget.generated.h"

UCLASS()
class MODULE_API USpaceListWidget: public UUserWidget
{
  GENERATED_BODY()

public:
  void NativeConstruct();

private:
  void OnSpaceAdded(FCavrnusSpaceInfo& SpaceInfo);
  void OnSpaceUpdated(FCavrnusSpaceInfo& SpaceInfo);
  void OnSpaceRemoved(FCavrnusSpaceInfo& SpaceInfo);
  
  FCavrnusBinding JoinableSpacesBinding;
  
  FCavrnusSpaceInfoEvent SpaceAdded;
  FCavrnusSpaceInfoEvent SpaceUpdated;
  FCavrnusSpaceInfoEvent SpaceRemoved;
  
  // USpaceWidget - theoretical list item or button that displays one joinable space
  TMap<FString, USpaceWidget*> SpaceWidgets;
};

SpaceListWidget.cpp

Code Block
#include "SpaceListWidget.h"
#include "CavrnusFunctionLibrary.h"

USpaceListWidget::NativeConstruct()
{
  Super::NativeConstruct();
  
  SpaceAdded.BindUFunction(this, GET_FUNCTION_NAME_CHECKED(USpaceListWidget, OnSpaceAdded));
  SpaceUpdated.BindUFunction(this, GET_FUNCTION_NAME_CHECKED(USpaceListWidget, OnSpaceUpdated));
  SpaceRemoved.BindUFunction(this, GET_FUNCTION_NAME_CHECKED(USpaceListWidget, OnSpaceRemoved));
  
  JoinableSpacesBinding = UCavrnusFunctionLibrary::BindJoinableSpaces(OnSpaceAdded, OnSpaceUpdated, OnSpaceRemoved);
}

void USpaceListWidget::OnSpaceAdded(FCavrnusSpaceInfo& SpaceInfo)
{
  if (!SpaceWidgets.Contains(SpaceInfo.SpaceId))
  {
    // Received a new space ID. Create a new widget and add it to the list.
    USpaceWidget* NewWidget = CreateWidget<USpaceWidget>();
    NewWidget->Initialize(SpaceInfo);
    SpaceWidgets.Add(SpaceInfo.SpaceId, NewWidget);
  }
}

void USpaceListWidget::OnSpaceUpdated(FCavrnusSpaceInfo& SpaceInfo)
{
  if (SpaceWidgets.Contains(SpaceInfo.SpaceId))
  {
    // Update this listing.
    SpaceWidgets[SpaceInfo.SpaceId]->UpdateSpaceInfo(SpaceInfo);
  }
}

void USpaceListWidget::OnSpaceRemoved(FCavrnusSpaceInfo& SpaceInfo)
{
  if (SpaceWidgets.Contains(SpaceInfo.SpaceId))
  {
    // This widget is no longer necessary.
    SpaceWidgets[SpaceInfo.SpaceId]->BeginDestroy();
    SpaceWidgets.Remove(SpaceInfo.SpaceId);
  }
}