Array of UObject ptrs(e.g. UActorComponent)

Hi there,

I’m a newbie to UE4, so my question is, how to handle a set of components in an actor (not define them one by one manually) , with CORRECT GC behavior.

I’ve tried as below, but crashed when dynamically adding new component into it …

class AFoo : public AActor
{
public:
...
TArray<UTextRenderComponent*> testArray;
...
}

And as far as i know, UTextRenderComponent* testArray[10]; is not correct either.

Any reply or advice appreciated!

On your header you need to declare your array like this

UPROPERTY()
TArray<UTextRenderComponent*> TextArray;

Now, to dynamically create a component at runtime:

UTextRenderComponent* NewText = NewObject<UTextRenderComponent>(this); 
// this reference to your Actor as Outer (necessary for GC)
NewText->RegisterComponent(); 
//You need to call it manually since you create this component at runtime

//Make what you want like set text, attach to component, etc..

TextArray.Add(NewText);

Also there is some built-in function to get an Array of UActorComponent from your actor, maybe better in some case :slight_smile:

Sorry for the late reply, I’ve tested that and it works well, THX!

btw, u mentioned that
there is some built-in function to get an Array of UActorComponent from your actor, maybe better in some case”,
do u mean by “using GetCompoentXXX() functions to find those components when needed” a better way than “saving them in an separate member array”?(better efficiency? better robustness? or some other advantages?)

Much apprieciated!

Yeah using GetComponentsByClass will give you all registered components of this class and avoid you to manage manually your TextArray. Both are good :slight_smile:

got it. thx~~