Download

Using a c++ interface to send messages between blueprints?

I’m having trouble coming up with an elegant way to create a messaging system (that can be leveraged during runtime) that can be used with blueprints and c++, what I’ve got leaves me with a fair bit of redundancy and difficult to manage code.

For example in my interface I’ve got:



USTRUCT(BlueprintType)
struct FObserverMessageInfo
{
  GENERATED_USTRUCT_BODY()

  UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interactive")
  AActor* InputObject;

  UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Interactive")
  FName MessageName;
}

UINTERFACE(Blueprintable)
class UInteractiveInterface : public UInterface
{
  GENERATED_UINTERFACE_BODY()
}
class IInteractiveInterface
{

  GENERATED_IINTERFACE_BODY()
 
  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category="Messaging", meta = (FriendlyName = "On Message (bool)"))
  void OnMessageBool(AActor* Sender, FName MessageName, bool Data);

  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category="Messaging", meta = (FriendlyName = "On Message (int32)"))
  void OnMessageInt(AActor* Sender, FName MessageName, int32 Data);

  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category="Messaging", meta = (FriendlyName = "On Message (float)"))
  void OnMessageFloat(AActor* Sender, FName MessageName, float Data);

  UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category="Messaging")
  void AddObserver(AActor* Observer, FName MessageName);
}


What it does is lets say we have an object that has multiple variables or events it wants to notify other objects of (at least when a change occurs). An object will create an array of FObserverMessageInfo for each relevant event which stores a pointer to any object that wants to receive the event and a FName which that object uses in a switch statement to determine what to do with the data. Anytime a relevant variable changes a OnMessage event will be fired off and each observing object will be notified of the new variable value.

Here’s where my troubles begin.

-Each c++ class or blueprint that implements this interface which has an event it wants to notify other objects of will be required to reimplement the same method of iterating through the array of FObserverMessageInfo’s and calling OnMessage on them. The same goes for the AddObserver function. It’s a small amount of redundancy but it’s still annoying.

-The functions and struct use AActor* as opposed to IInteractiveInterface to store/pass objects around. This is because blueprint does not play nicely with Interface typed variables (at least when trying to assign a blueprint to an editable Interface variable using the details panel). This is not ideal, but I can live with it if I have to.

I may just be over thinking it, but it feels like I’m going about this the wrong way. Any suggestions?