Add Component based on Value of UPORPERTY

Hello,

I have two Classes: UItem and UWeapon. Both classes have the same parent class. An Item, can have a simple static mesh, while a weapon has a skeletal mesh, since they are animated. Now, I have an Actor Called ItemPickup. This Pickup has a UPROPERTY, that contains a UClass which is a SubClass of BaseItem, that is the parent Class of Item and Weapon. In my Pickup Actor, I now want to add either a StaticMesh Component or a SkeletalMesh Component, based on the Item class that has been assigned to the actor. I tried adding the component in OnConstruction:

UWeapon* testWeapon = Cast<UWeapon>(item);
		if (testWeapon)
		{
			USkeletalMeshComponent* IMC = ConstructObject<USkeletalMeshComponent>(USkeletalMeshComponent::StaticClass(), this, "ItemMeshComponent");
			IMC->SkeletalMesh = testWeapon->thirdPersonMesh;
			ItemMeshComponent = IMC;
			ItemMeshComponent->RegisterComponent();
			ItemMeshComponent->AttachTo(GetRootComponent());


		}

I created a BP that is derived of my Pickup Actor. When I drag the actor to the editor window, it shows the component, but as soon as I drop the actor, the editor crashes. This is the a pastebin of the Backtrace: > UE4Editor-Engine.dll!USceneComponent::OnComponentDestroyed() Zeile 669 C++ - Pastebin.com

Anybody having a clue, what I am doing wrong?

Hello, Brainshack

I am sorry to hear about your issue.
It is likely that in this situation the component gets created multiple times but never gets cleaned.
Thus, please add this line to your code to ensure that it will be initialized properly :

IMC->CreationMethod = EComponentCreationMethod::UserConstructionScript;

Hope this helped!

Good luck!

Got it to work with your help. Thanks a lot.