The documentation and examples I have found for adding a component via c++ all make use of ‘Components.Add’, including the tutorial here: LightSwitch C++ Only
Using the code in that tutorial as an example, for me the Components collection on class AActor is inaccessible.
(eg. 'Components.Add(PointLight1); ’ does not compile.)
The header for AActor lists a function named ‘AddComponent’, is that equivalent in purpose? Or am I missing something?
I tried the AddComponent function and it works well, I’m just curious why I cannot see the Components collection directly (I’m guessing it was deprecated?).
Here is the modified .cpp file for the lightswitch c++ only tutorial, compiles & works properly:
(taken from after the include directives)…
ALightSwitchCodeOnly::ALightSwitchCodeOnly(const class FPostConstructInitializeProperties& PCIP)
DesiredBrightness = 15.0f;
PointLight1 = PCIP.CreateDefaultSubobject<UPointLightComponent>(this, "PointLight1");
PointLight1->SetBrightness(DesiredBrightness); //direct access was deprecated
PointLight1->bVisible = true;
RootComponent = PointLight1;
AddComponent(FName("UPointLightComponent"), true, FTransform(FVector()), PointLight1);
Sphere1 = PCIP.CreateDefaultSubobject<USphereComponent>(this, TEXT("Sphere1"));
Sphere1->AttachParent = RootComponent;
AddComponent(FName("USphereComponent"), true, FTransform(FVector()), Sphere1);
void ALightSwitchCodeOnly::OnOverlap(AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
if (OtherActor && (OtherActor != this) && OtherComp)
I think they encapsulate it, such that messing around with the collections is harder but nevertheless very interesting behavior. Can u try to delete the line with AddComponent? Does it still work? It seems Unreal also uses reflection internally to register components
Look at the generic Method GetComponents() in Actor.h, I’m just curious but I think you do not need the call of AddComponent(). It may give you a better creation performance if Unreal does not use reflection though but I did not use it and my Components show up.
The Components array is something we actually removed very recently, we’ll try and get the docs updated for the next release! Things are easier now, you simply create the component, assign it to your own variable, and you are done If you do not want the component to be registered automatically, you can set bAutoRegister to FALSE.
The AddComponent function is only intended to be used by Blueprints.
Thanks James, much appreciated.
JamesG: Can you give an example of how to create the component and assign to a variable in C++ instead of calling AddComponent?