How to call this funktion

Hello, I am quite inexperienced with C++, so please answer as simple as possible. I have the function AttachWeapon in APistol (

void APistol::AttachWeapon(ACharacterM* TargetCharacter)
{
	Character = TargetCharacter;;
	if (Character != nullptr)
	{
		// Attach the weapon to the Character
		FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget, true);
		GetOwner()->AttachToComponent(Character->GetCharacterMesh(), AttachmentRules, FName(TEXT("GripPoint")));

		// Register so that Fire is called every time the character tries to use the item being held
		Character->OnUseItem.AddDynamic(this, &APistol::Fire);
	}
}

) and I want to call it in ACharacterM(

void ACharacterM::BeginPlay()
{
	Super::BeginPlay();

	APistol::AttachWeapon(x);
	
}

). However, I can’t do it because I don’t know what goes where the x is.

You’ll need to create a new instance of your pistol actor first, and then call AttachWeapon(this) on it.

APistol* NewPistol = GetWorld()->SpawnActor<APistol>();
if (NewPistol)
{
    NewPistol->AttachWeapon(this);
}

Doing this in your character’s BeginPlay() should work. Keep in mind this will spawn the base APistol class, if you want to spawn a derived blueprint, you’ll need to get the blueprint’s class (through, for example, a TSubclassOf<APistol> in your character’s properties), and use it to spawn the pistol.

APistol* NewPistol = GetWorld()->SpawnActor<APistol>(PistolClass);
if (NewPistol)
{
    NewPistol->AttachWeapon(this);
}
1 Like