Hi,
I’m working on a simple FPS based on UE5 fps template, and I want to implement reloading. I managed to do that, but the problem is that I have different weapons and ammo types, and I need to reload different ammo type based on the weapon I’m currently holding. In my TP_WeaponComponent I declared a FString variable, that stores weapon’s name (it is set in the weapon’s BP). In order to reload the right type of ammo, I’m just comparing that variable with strings in ‘if’ statement. It works fine, but it looks like sh*t (I have two weapons now, and I’m planning 4, but adding more weapons and/or ammo types will look terrifying), and it’s not difficult to make a mistake (e.g. writing Assaylt instead of Assault). So, is there any better way for me to do it?
My Reload() function in UTP_WeaponComponent:
void UTP_WeaponComponent::Reload()
{
if (Character == nullptr || Character->GetController() == nullptr)
{
return;
}
int AmmoNeededForReload{ MagSize - AmmoLeftInMag };
if (WeaponName == "Assault")//Weapon name is FString variable that stores weapon's name
{
if (Character->GetEquipmentComponent()->AssaultRifleAmmo >= AmmoNeededForReload)
{
AmmoLeftInMag += AmmoNeededForReload;
Character->GetEquipmentComponent()->AssaultRifleAmmo -= AmmoNeededForReload;
}
else
{
AmmoLeftInMag += Character->GetEquipmentComponent()->AssaultRifleAmmo;
Character->GetEquipmentComponent()->AssaultRifleAmmo = 0;
}
}
else if (WeaponName == "Grenade")
{
if (Character->GetEquipmentComponent()->GrenadeLauncherAmmo >= AmmoNeededForReload)
{
AmmoLeftInMag += AmmoNeededForReload;
Character->GetEquipmentComponent()->GrenadeLauncherAmmo -= AmmoNeededForReload;
}
else
{
AmmoLeftInMag += Character->GetEquipmentComponent()->GrenadeLauncherAmmo;
Character->GetEquipmentComponent()->GrenadeLauncherAmmo = 0;
}
}
else
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Wrong Weapon Name"));
}