Reputation: 107
I'm creating a third person laser tag shooter thing for fun and I'm having difficulty creating my weapon hierarchy. My main problem is my editor is crashing from an access error from some errors from pointers in my code and I don't understand pointers enough to be able to figure this out myself.
I'm trying to add a weapon to my default pawn ALTPlayer. I'm doing this by using TSubclassOf to ensure I can only attach children of ALTWeapon to my character
If it helps my explanation, current hierarchy is:
APawn->ALTWeapon->ALaserGun
... and I'm planning on adding a bunch more classes with ALTWeapon as their parent. I'm hoping this will make my code organized and easier to code different functionality for each weapon.
With that in mind, I'll start with my ALTPlayer.h file. Here I declare WeaponClass as my subclass variable
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "LTPlayer.generated.h"
class ALTWeapon;
UCLASS()
class LASERTAG_API ALTPlayer : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values
ALTPlayer();
// Player weapon
UPROPERTY(EditAnywhere)
TSubclassOf<ALTWeapon> WeaponClass;
};
Now I'll move into my ALTPlayer.cpp file. Here I'm trying to create an ALaserGun object that's stored in WeaponClass. (I'm also not sure if this is exactly how I'm supposed to do this)
#include "LTPlayer.h"
#include "LaserGun.h"
// Sets default values
ALTPlayer::ALTPlayer()
{
// Creating Weapon
this->WeaponClass->GetDefaultObject<ALaserGun>();
}
At this point, I expect to see an ALaserGun component in my blueprint child of ALTPlayer. Although, since I have the pointer issue that's crashing my editor, I don't know if that's what this code produces.
If anyone has any insight on how to fix my pointers so that I don't get an access violation, that would be awesome!
Upvotes: 2
Views: 2031
Reputation: 1212
You're attempting to dereference WeaponClass when you try to access its default object but it hasn't yet been assigned to anything.
You can initialize it in the constructor initializer list, like so:
ALTPlayer::ALTPlayer()
: WeaponClass(ALTWeapon::StaticClass())
{
}
If this is a class that can be set in a Blueprint default, you can also ensure that it has a value by setting it in PreInitializeComponents:
Declaration:
//~ Begin AActor Interface
virtual void PreInitializeComponents() override;
//~ End AActor Interface
Definition:
void ALTPlayer::PreInitializeComponents()
{
Super::PreInitializeComponents();
// Fallback to default Weapon class if none was specified.
if (WeaponClass == nullptr)
{
UE_LOG(LogGameMode, Warning, TEXT("No WeaponClass was specified in %s (%s)"), *GetName(), *GetClass()->GetName());
WeaponClass = ALTWeapon::StaticClass();
}
}
Upvotes: 2