Skip to content

Instantly share code, notes, and snippets.

@johnfredcee
Created November 12, 2023 10:32
Show Gist options
  • Save johnfredcee/a75b8c249cfa33c8760d60a10f71f2b6 to your computer and use it in GitHub Desktop.
Save johnfredcee/a75b8c249cfa33c8760d60a10f71f2b6 to your computer and use it in GitHub Desktop.
Creating and populating a spline component at runtime in C++ in Unreal
/**
* Generate a spline we will later use to extrue a road from a set of points
*/
void ARoadNetwork::GenerateRoadSplines(const TArray<FVector>& InPoints)
{
// SplineBeingEdited is an Editor Only property we use to see our new component
// in the details panel as it won't show up otherwise
#if WITH_EDITORONLY_DATA
if (SplineBeingEdited == nullptr)
{
#endif
// create the component
USplineComponent* SplineComponent = NewObject<USplineComponent>(this);
#if WITH_EDITORONLY_DATA
// ensure it appears in the details panel
SplineBeingEdited = SplineComponent;
#endif
SplineComponent->RegisterComponent();
SplineComponent->ComponentTags.Add(TEXT("Generated"));
// set the spline to default state, but with no points
SplineComponent->ResetToDefault();
SplineComponent->ClearSplinePoints();
// Iterate over our input points and add spline points to the spline component
for (const auto& InPoint : InPoints)
{
int32 AddIdx = SplineComponent->GetNumberOfSplinePoints();
SplineComponent->AddSplinePointAtIndex(InPoint, AddIdx, ESplineCoordinateSpace::Local);
}
// ensure spline is updated
constexpr bool bUpdateSpline = true;
SplineComponent->SetClosedLoop(bUpdateSpline);
// attach spline component to root
FAttachmentTransformRules Rules(FAttachmentTransformRules::KeepRelativeTransform);
SplineComponent->AttachToComponent(RootComponent, Rules);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment