If statement causes crashes when given anything declared in header

if statements Inside Actor Component cause crashes when given (int, bool, float) that are declared in the actor components header

is this something to do with ActorComponent and its header and the way things should be declared

charater .h

class UMyActorComponent* ActorComp;

character cpp

#include "MyActorComponent.h"

void AMyCharacter::BeginPlay()
{
	Super::BeginPlay();

	ActorComp->CompFunc();
}

ActorComponent .h

bool BB;

void CompFunc();

ActorComponent cpp

#include "Engine.h"

UMyActorComponent::UMyActorComponent()
{
	BB = true;
}

void UMyActorComponent::CompFunc()
{
	if (BB)
	{
		// Nothing
	}
	else
	{
		// nothing
	}
}

the crash Log says Unhandled Exception: EXCEPTION_ACCESS_VIOLATION reading address 0x000000c0

Is ActorComp valid?

if (IsValid(ActorComp))
{
   ActorComp->CompFunc();
}

Wow i didn’t realize it wasn’t valid Why is this it is not valid

i thought

  class UMyActorComponent* ActorComp = nullptr;

**was all i needed to do **

and

  ActorComp->CompFunc();

was how i called functions in it actorcomponent

How are you setting ActorComp? Is ActorComp a UPROPERTY?

Only use IsValid with UPROPERTY, otherwise, a simple nullptr check.

     if (ActorComp != nullptr)
     {
        ActorComp->CompFunc();
     }

Also, always initialize your pointers:

 class UMyActorComponent* ActorComp = nullptr;

i have tried all of what you said but the ActorComponent isnt valid

character .h

class UMyActorComponent* ActorComp = nullptr;

Character cpp

if (ActorComp != nullptr)
{
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Purple, TEXT("actor comp valid"));
	//ActorComp->CompFunc();
}

If it’s not valid, then how are you assigning ActorComp?

Are you creating a MyActorComponent component? How are you getting its reference?

Thankyou **But ** it is giving me an error with SetupAttachment

it says UMyActorComponent has no member setup attachment

I wish it was that simple.

Is MyActorComponent a component for MyCharacter? If so, then use the same process that is used to create any other component in the character’s construtor:

ActorComp = CreateDefaultSubobject<UMyActorComponent>(TEXT("MyActorComponent"));
ActorComp->SetupAttachment(RootComponent);

And:

 UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
 class UMyActorComponent* ActorComp = nullptr;

Which means, you now can use IsValid instead of nullptr to check if the pointer is valid.

Sorry my bad. Remove that line.

Thank you so much EvilCleric

**I was truely stumped **

That fixed it