I’m trying to convert a weapon system I prototyped in blueprint to C++, but I’m running across a snag when trying to cast my weapon class’s owner to my player character.
I can’t just reference the character in the weapon header because that creates a circular dependency, but as is, the weapon actor doesn’t know that the character exists.
Hey!
First to avoid circular depedency use forward declaration!
That means put in BaseWeapon.h after includes one line with class AWeaponSystem_CodeCharacter;
After that you can put YOUR character class.h to BaseWeapon.cpp
Do same with BaseWeapon in your character class and all of your circular depedency will fly away
Wow, that worked pretty quickly. I never knew about forward declaration before, but that is really helpful.
In case anyone wants to see what I did, here’s the top of my .h file and .cpp file:
.h file:
#include "stuff.h"
// Forward declaration of Character class
class ACodeCharacter;
UCLASS()
class WEAPONSYSTEM_CODE_API ABaseWeapon : public AActor
{
GENERATED_BODY()
ACodeCharacter* OwningChar;
public:
// Sets default values for this actor's properties
ABaseWeapon();
//...
.cpp file:
#include "BaseWeapon.h"
#include "CodeCharacter.h"
// My other functions...
void ABaseWeapon::AttachWeaponToCharacter(FName SocketName)
{
OwningChar = Cast<ACodeCharacter>(GetOwner());
}