From ac9c8981b917d2ebc7ed63d3cf18e0222e4cd63c Mon Sep 17 00:00:00 2001 From: Louis Hobbs Date: Tue, 24 Jan 2023 02:54:17 +0000 Subject: [PATCH] Fix out of range array crashes when removing weapon from inventory --- Source/Nakatomi/PlayerCharacter.cpp | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/Source/Nakatomi/PlayerCharacter.cpp b/Source/Nakatomi/PlayerCharacter.cpp index d805c70..40150b4 100644 --- a/Source/Nakatomi/PlayerCharacter.cpp +++ b/Source/Nakatomi/PlayerCharacter.cpp @@ -164,6 +164,10 @@ void APlayerCharacter::BeginFireCallback(const FInputActionInstance& Instance) OnFire(); + if (CurrentWeapon == nullptr) + { + return; + } if (CurrentWeapon->GetWeaponProperties()->IsAutomatic) { @@ -375,7 +379,12 @@ void APlayerCharacter::AddWeaponToInventory(TSubclassOf weapon) } void APlayerCharacter::RemoveWeaponFromInventory(int i) -{ +{ + if (WeaponInventory[i] == CurrentWeapon) + { + CurrentWeapon = nullptr; + } + WeaponInventory[i]->Destroy(); WeaponInventory.RemoveAt(i); @@ -397,7 +406,7 @@ void APlayerCharacter::RemoveWeaponFromInventory(AWeapon* weapon) { if (int index = WeaponInventory.Find(weapon) != INDEX_NONE) { - RemoveWeaponFromInventory(index); + RemoveWeaponFromInventory(index - 1); } } @@ -420,16 +429,16 @@ void APlayerCharacter::OnFire() CurrentWeapon->DecrementAmmoCount(1); - if (CurrentWeapon->GetAmmoCount() == 0) - { - RemoveCurrentWeaponFromInventory(); - } - CurrentWeapon->PlayFireSoundAtLocation(GetActorLocation()); // TODO: Play some animation here CurrentWeapon->SetCurrentWeaponStatus(WeaponState::Cooldown); + + if (CurrentWeapon->GetAmmoCount() == 0) + { + RemoveCurrentWeaponFromInventory(); + } } void APlayerCharacter::WeaponCooldownHandler()