problem with nullptr

Hi!
I’m new to Unreal and I think I don’t understand how null pointers work.
In my lvl I’ve got a door that’s opening and I want to add a sound to it. I made all needed declarations in .h file:


#include "Components/AudioComponent.h"
UPROPERTY()
UAudioComponent* AudioComponent = nullptr;

The problem is, when I try to find my sound with


AudioComponent = GetOwner()->FindComponentByClass<UAudioComponent>();

If I do it with BeginPlay() on the start of the game, it does well and find my sound. but when I do it with TickComponent(), to check each frame if the door is close/open I get AudioComponent == nullptr.

So basically the question is why when I start the game I find the sound but I can’t find it in each frame?

You have declared an audio component pointer and told it to point to nothing.
Hence, null pointer (nullptr).

You have to create an UAudioComponent object for the variable to point at.
This can be in numerous places, but is often done inside the class constructor.


AudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("MyAudioComponent0"));

Would suggest having a look at some C++ tutorials, UE4 specific or otherwise, before continuing.

Thanks for help but still, tried to put this line of code



 AudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("MyAudioComponent0")); 

in the **.h **file or in .cpp file, changing the “MyAudioComponent0” to the name *GetOwner() → GetName() but unreal crushes…

Some things are not clear: are you creating a component or it’s a just an actor?

If your door is just an actor (if not tell us), then here is one example on how to use the audiocomponent:

In the .h file:



...
protected:
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AudioEffects")
        class UAudioComponent* AudioComponent = nullptr;

    UFUNCTION(BlueprintCallable, Category = "AudioEffects")
        void PlayOpenDoorSound();
...


In the .cpp file:



#include "MyDoor.h"
#include "Components/AudioComponent.h"


// Sets default values
AMyDoor::AMyDoor()
{
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    ...

    AudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("OpenDoorAudio"));
    AudioComponent->bAutoActivate = false;
}


void AMyDoor::PlayOpenDoorSound()
{
    if (AudioComponent)
    {
        AudioComponent->Play();
    }
}

...


Create a BP with AMyDoor as the parent, set the sound and call PlayOpenDoorSound() in BP when you need it.

Could you give us a little more info on what you doing?