I have made a weapon switching system its not 100% done like the models are not in place but the basic switching is there. I am going to put my code of how i made it to switch and anything that you notice that is inefficient and can cause a problem could you please tell me and also include a way of how i can make it better or just pseudo code it as i dont want to be spoon feed so i can learn something from it. Also could you add a reason why i would need to change it like what problems could it cause etc.
first i spawn my primary and secondary guns at BeginPlay() i set the secondary gun to hidden and primary gun to visible and i also set my current gun to the primary weapon as thats the starting gun i want.
PrimaryWeapon = GetWorld()->SpawnActor<AWeaponBase>(PrimaryWeaponBlueprint);
PrimaryWeapon->AttachToComponent(Mesh1P, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("WeaponSocket"));
PrimaryWeapon->SetActorHiddenInGame(false);
PrimaryWeapon->Character = this;
SecondaryWeapon = GetWorld()->SpawnActor<AWeaponBase>(SecondaryWeaponBlueprint);
SecondaryWeapon->AttachToComponent(Mesh1P, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("WeaponSocket"));
SecondaryWeapon->SetActorHiddenInGame(true);
SecondaryWeapon->Character = this;
CurrentWeapon = PrimaryWeapon;
In my character class i make a ChangeWeapon() Method and add the code to allow the primary and secondary guns to change.
void ALearnProjectCharacter::ChangeWeapon() {
if (CurrentWeapon == PrimaryWeapon || CurrentWeapon == nullptr) {
CurrentWeapon = SecondaryWeapon;
PrimaryWeapon->SetActorHiddenInGame(true);
SecondaryWeapon->SetActorHiddenInGame(false);
UE_LOG(LogTemp, Warning, TEXT("SecondaryEquipped"))
}
else if(CurrentWeapon == SecondaryWeapon) {
CurrentWeapon = PrimaryWeapon;
PrimaryWeapon->SetActorHiddenInGame(false);
SecondaryWeapon->SetActorHiddenInGame(true);
UE_LOG(LogTemp, Warning, TEXT("PrimaryEquipped"))
}
}
Then i have an OnFire() Method and it looks for the CurrentGun when switching weapons the current gun will change as you can see from the code and it will fire the correct fire method for the gun
void ALearnProjectCharacter::OnFire() {
CurrentWeapon->WeaponFire();
}
That’s basically the code apart from the variables which there is no need to add this all does work but im just looking for alternate ways to make my code more efficient and remove unnecessary code.
Thanks for all reply’s in advance.