I keep having this problem, I have spend a lot of time trying to figure out what’s wrong with my code but I can’t seem to figure it out.
I am trying to spawn a gun actor in my character class, I set the mesh with a blueprint based on the Gun class which has a mesh and a rootComponent and I want to attach this to a socket called Gun which I made in my character skeleton.
The subclass which I set the mesh within my editor:
UPROPERTY(EditAnywhere, Category = "Gun")
TSubclassOf<AGun> WeaponClass;
the components in my Gun class:
Root = ObjectInitializer.CreateDefaultSubobject<USceneComponent>(this, TEXT("Root"));
Mesh = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this,TEXT("Mesh"));
Mesh->AttachTo(Root);
I call the EquipWeapon(); in my FirstPlayer constructor
void AFirstPlayer::EquipWeapon()
{
FActorSpawnParameters SpawnInfo;
SpawnInfo.bNoCollisionFail = true;
FRotator setRotation = GetActorRotation();
AGun* SpawnedGun = GetWorld()->SpawnActor<AGun>(WeaponClass, this->GetActorLocation(), setRotation, SpawnInfo);
if (SpawnedGun) {
SpawnedGun->AttachWeaponToPawn(this, "Gun");
}
}
These are the methods I use to actually attach it:
USkeletalMeshComponent* AGun::getPawnSkeletalComp(FString ComponentName)
{
TArray<UActorComponent*> Components;
USkeletalMeshComponent* ArmMesh = NULL;
if (OwningPawn)
OwningPawn->GetComponents(Components);
for (UActorComponent* Comp : Components)
{
ArmMesh = Cast<USkeletalMeshComponent>(Comp);
if (ArmMesh)
{
if (ArmMesh->GetName() == ComponentName)
return ArmMesh;
}
}
return NULL;
}
void AGun::AttachWeaponToPawn(APawn* WeaponOwner, FString SkeletalCompName)
{
OwningPawn = WeaponOwner;
SetOwner(WeaponOwner);
USkeletalMeshComponent* ArmMesh = getPawnSkeletalComp(SkeletalCompName);
if (ArmMesh) {
AttachRootComponentTo(ArmMesh, FName(*SkeletalCompName));
}
}
The editor keeps crashing on startup and when I delete the intermediate, binaries and saved restart my computer and do a completely rebuild and everything (after I removed these pieces of code) it seems to work again. But then trying to add the code will crash the editor and will keep it from detecting any new changes I make to the code after that which is why I have to repeat this process over and over again.
It’s extremely difficult to test like this.