Single Fire Convert to Multiple + Reload + Ammo

Let’s create some function and value:
Before: Project Settings --> Input --> Bindings --> Action Mappings --> add “Reload” and R button

  1. Open your ShooterCharacter.h
    1.a) add in public section
    FTimerHandle ShootTimer;

1.b) add in private section

    void Shoot();
	void StopShooting();
	void Reload();
	bool LeftMouseHeld = true;
	
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Attack", meta = (AllowPrivateAccess = "true"))
	int DefaultAmmo;
	int Ammo;
	
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Attack", meta = (AllowPrivateAccess = "true"))
	float FireRate = 0.5f;
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Attack", meta = (AllowPrivateAccess = "true"))
	float FireRepeat = 1.0f;
  1. Open your ShooterCharacter.cpp
    2.a) add in top
#include "TimerManager.h"

2.b) add in begin play

Ammo = DefaultAmmo;

2.c) Scroll up find SetupPlayerInputComponent add this

PlayerInputComponent->BindAction(TEXT("Shoot"), EInputEvent::IE_Pressed, this, &AShooterCharacter::Shoot);
PlayerInputComponent->BindAction(TEXT("Shoot"), EInputEvent::IE_Released, this, &AShooterCharacter::StopShooting);
PlayerInputComponent->BindAction(TEXT("Reload"), EInputEvent::IE_Pressed, this, &AShooterCharacter::Reload);

2.d) Scroll Down

void AShooterCharacter::Shoot()
{		
		if (Ammo != 0)
		{
			GetWorldTimerManager().SetTimer(ShootTimer, this, &AShooterCharacter::Shoot, FireRepeat, true, FireRate);
			Gun->PullTrigger();
			Ammo--;
		}
		else if (Ammo == 0)
		{
			GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
			LeftMouseHeld = true;
			Reload();			
		}
}
void AShooterCharacter::StopShooting()
{
	GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
	LeftMouseHeld = false;
}

void AShooterCharacter::Reload()
{
	UE_LOG(LogTemp, Warning, TEXT("Reloading"));
	Ammo = DefaultAmmo;
	if(LeftMouseHeld == false)
	{
		GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
	}else
	{
		LeftMouseHeld = true;
		GetWorld()->GetTimerManager().ClearTimer(ShootTimer);
		GetWorldTimerManager().SetTimer(ShootTimer, this, &AShooterCharacter::Shoot, FireRepeat, true, FireRate);
	}
}

Is this code of yours fully compatible with the rest of the this lecture series or would I need to do a lot of jiggery-pokery to get it to work?

Because if it is I am going to add it to my project to add in some extra functionality!

Thanks for posting!


PS: Just remember to put:

FTimerHandle ShootTimer;

in the header file to save some revision headaches and to actually set/save/compile the DefaultAmmo in the Blueprint.

Privacy & Terms