How to use delegates as parameter

Hi! I’m pretty new in using delegates in Unreal and I’m kind of stuck. So I have a class where I defined a delegate and its constructor takes it in as a parameter: WorldGeneration.h


DECLARE_DELEGATE_TwoParams(FWorldGenerationCallback, TArray&, MeshData*);

 class PROCEDURALWORLD_API WorldGeneration: public FRunnable
 {
 public:
     WorldGeneration(WorldStats* stats, FWorldGenerationCallback& callback);
     ~WorldGeneration();
 //some other functions
 private:
     TArray mGrid;
     WorldStats* mStats;
     FWorldGenerationCallback mFinishCallback;
     MeshData* mMeshData;
 };

WorldGeneration.cpp:


WorldGeneration::WorldGeneration(WorldStats* stats, FWorldGenerationCallback& callback)
{
     mStats = stats;
    //delegate is used in some other function inside WorldGeneration class with .Execute 
    mFinishCallback = callback; 
}

Now inside the other class I’m trying to create the WorldGeneration instance and send the function I want to be using as delegate GeneratedWorld.cpp


void AGeneratedWorld::LoadMeshData(TArray& createdGrid, MeshData* meshData)
{
    //function I want to send as delegate
}

void AGeneratedWorld::RequestWorldGeneration()
{
    WorldStats* stats = new WorldStats();
    //more code

    //I don't know how to send the LoadMeshData function
    WorldGeneration* worldGeneration = new WorldGeneration(stats, &AGeneratedWorld::LoadMeshData);
}

I know that in Unity you can just pass in the name of the function like I’ve done in the code above and it works normally… What am I doing wrong?

Well, &AGeneratedWorld::LoadMeshData just created a function pointer. You need a delegate there. So you want something similar to



void AGeneratedWorld::RequestWorldGeneration()
{
        WorldStats* stats = new WorldStats();
        FWorldGenerationCallback Callback = FWorldGenerationCallback::CreateRaw(this, &AGeneratedWorld::LoadMeshData);
        WorldGeneration* worldGeneration = new WorldGeneration(stats, Callback);
}


This is the closest to the metal way but you really should define LoadMeshData() as a UFUNCTION(). Then you could use FWorldGenerationCallback::CreateUObject or FWorldGenerationCallback::CreateUFunction to create the delegate. You can find more about delegates here:

It doesn’t need to be a UFUNCTION, you can (and should) just use CreateUObject in place of CreateRaw above.

My bad, I thought in order to use CreateUObject() you needed the UFUNCTION() preprocessor. I guess you only need it for CreateUFUnction()

You only need a UFUNCTION when using dynamic delegates. That allows you to add the delegate by name.