I am currently developing a class that manages abilities for different classes of characters. Different characters will have different abilities, and MyAbilityManager is acting as the authority.
I am getting clean compilations but my game is crashing when I press the input key. Here is the code that is relevant to my issue.
The log reads “Access violation code c0000005 (first/second chance not available)” It references this line in AbilityManager.cpp “return Ability[AbilityNumber];”
The only thing I can think of is maybe I didn’t initialize the Ability array properly in the constructor and I’m returning a null reference when the call to GetAbility(…) is made. Is there another place I should be initializing this array or perhaps another class that is better to inherit from than UObject?
***MyCharacter.h
#include "AbilityManager.h"
...
template<int Index>
void ToggleAbility() { ToggleAbility(Index); }; // Template function for Input
void ToggleAbility(int AbilityNumber);
UAbilityManager* AbilityManager;
***MyCharacter.cpp
void AMyCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
...
InputComponent->BindAction("TogglePrimaryAbility", IE_Pressed, this, &AMyCharacter::ToggleAbility<0>);
InputComponent->BindAction("ToggleSecondaryAbility", IE_Pressed, this, &AMyCharacter::ToggleAbility<1>);
...
}
void AMyCharacter::ToggleAbility(int AbilityNumber)
{
AbilityManager->ToggleAbility(AbilityNumber);
}
***AbilityManager.h
#pragma once
#include "Ability.h"
#include "AbilityManager.generated.h"
class Ability;
UCLASS(Within = MyCharacter)
class SHOOTERGAME_API UAbilityManager : public UObject
{
GENERATED_UCLASS_BODY()
public:
...
UFUNCTION(exec)
UAbility* GetAbility(uint8 AbilityNumber);
void ToggleAbility(int AbilityNumber);
UPROPERTY()
TArray<class UAbility*> Ability;
...
};
***AbilityManager.cpp
UAbilityManager::UAbilityManager(const class FObjectInitializer& ObjectInitializer)
{
UAbility* AbilityToAdd = NewObject<UAbility>(UAbility::StaticClass());
Ability.AddUnique(AbilityToAdd);
}
void UAbilityManager::ToggleAbility(int AbilityNumber)
{
UAbility* AbilityToToggle = GetAbility(AbilityNumber);
if (AbilityToToggle->IsActive())
AbilityToToggle->Deactivate(); // Implementation currently set to display a debug message, nothing else
else if (CanActivate(AbilityNumber))
AbilityToToggle->Activate(); // Implementation currently set to display a debug message, nothing else
}
UAbility* UAbilityManager::GetAbility(uint8 AbilityNumber)
{
return Ability[AbilityNumber]; // Log says THIS is the line of code causing the editor to crash when I make a call to "TogglePrimaryAbility" in MyCharacter.
}
bool UAbilityManager::CanActivate(int AbilityNumber)
{
UAbility* AbilityToCheck = GetAbility(AbilityNumber);
if (AbilityToCheck->IsActive())
return false;
else
return true;
}