Why would creating spherecomponents this way crash Unreal?

I’m trying to generate a handful of USphereComponents to use as hitboxes, as a test I just tried to spawn them in my component’s BeginPlay:


USphereComponent* RHhitbox;
USphereComponent* LHhitbox;
UPointLightComponent* pointLight;


void UCombat::MapSockets(){ 
	pointLight = CreateDefaultSubobject<UPointLightComponent>(FName(TEXT("TestLight")));
	RHhitbox = CreateDefaultSubobject<USphereComponent>(FName(TEXT("RH Hit Sphere")));

Everything runs perfectly up until I execute MapSockets(), at which point the game and editor both crash. Is there anything obviously wrong with what I’m doing that would lead to this behavior?

CreateDefaultSubobject works only in constructor, use NewObject and then AddComponent. Remember that creating and removing components dynamically is pretty expensive don’t use it too intensively. You might consider using sweep traces instead:


Oh hey, that fixes it- thank you! :slight_smile:

I considered sweep tests earlier (I’m using this for melee hit detection), and the main reason they make me leery is because of the extra checks they entail: with a collision volume I can just enable a limb’s USphereComponent at the start of an attack animation and message any targets in OnBeginOverlapComponent().

Using sweep tests for the same function I would need to trigger the test from an animation event every damage frame, and implement something clumsy to keep the same attack from hitting twice, like giving the attacker a TArray, adding everyone who has been hit to that array, and adding a conditional check to the start of DoDamage() to check the current return against everyone who has already been messaged to take damage during the attack.

I don’t know the system well, however- do you think the second thing would still be more performant than dynamically creating hitbox volumes at runtime and doing collision checks during the attack?