PCG – Drive PCGGraph by code (C++)

By jjeromegerstch

there are some times where we want to control a PCG graph from the code of an actor that have it’s own little PCGComponent.

The first REALLY IMPORTANT thing is that PCG will not schedule your graph for execution if the owning actor have no bounds! So if you have an actor with only your PCG Component It’s “normal” that generate does nothing (up to 5.6 included)

so add a invisible no collision cube and hop you can now generate your graph on your custom actor with a PCG Component.

Once you have your actor with a PCG Component and something that gives you bounds you can either add a graph directly in the component or by code.

//Set a graph on the component.
PCGVisComponent->SetGraph(WorldPointVizualizerGraph);

once you have your graph you can generate it in code with:

//Generate the PCG graph referenced by this component
PCGVisComponent->Generate();

One big interest to drive a graph by code is to adjust your graph input parameters before generation! For that we can use the helper UPCGGraphParametersHelpers

UPCGGraph* currentGraph = PCGVisComponent->GetGraph();
if(currentGraph)
{
    UPCGGraphParametersHelpers::SetNameParameter(currentGraph, "WorldToVisualize", WorldToVisualize);
}

Nice ! We have a graph with parameters ready to be used. But what if you want to get what is in the Output of your graph ?

First it can help to know when this graph’s execution is over:

//Bind to the end of graph generation
PCGVisComponent->OnPCGGraphGeneratedDelegate.AddUObject(this, &APCGWorldDataVisualizer::OnPCGGraphGenerated);

Once you are in your end of generation function you can query the component get it’s Generated Output data.

void APCGWorldDataVisualizer::OnPCGGraphGenerated(UPCGComponent* Component)
{
	if (Component && Component->GetGraph())
	{
		for (FPCGTaggedData TaggedData : Component->GetGeneratedGraphOutput().TaggedData)
		{
			const UPCGData* WhatIWeallyReallyWant = TaggedData.Data.Get();
			//Do whatever you want with the data !
		}
	}
}

With that you already have a good start to drive your PCG graphs from code

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *