Creating a reference to a C++ actor in another class causes crashes

I created a C++ Actor, which works fine on its own (i.e. if I spawn it in the editor somewhere in the world it works as expected).

I’m trying now to create it inside another C++ Actor, in the constructor., like this:



MySecondActor::MySecondActor()
{
     // I create the actor and set it as invisible. mMyActor is defined in the header as "MyFirstActor *mMyActor"
     mMyActor = CreateDefaultSubobject<MyFirstActor>(TEXT(test));
     mMyActor->SetActorHiddenInGame(true);
}


The code above works and the editor doesn’t crash if I spawn MySecondActor in the world. I would like now to manipulate the reference to MyFirstActor at runtime now, but ANYTHING I do to it makes the edtor crash.

For example, if I do this:



void MySecondActor::BeginPlay()
{
     if(mMyActor != nullptr)
         mMyActor->SetActorHiddenInGame(false);
}


It crashes when calling mMyActor.SetActorHiddenInGame(false) saying “Access violation - code c0000005 (first/second chance not available)”.
Note that it passes the check with the nullptr, so the reference is somehow valid.

Right now the class MyFirstActor is basically empty. I only use the constructor like this:



MyFirstActor::MyFirstActor()
{
    USceneComponent *sceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
    RootComponent = sceneComponent;
}


I haven’t a clue of what is going on here. Please, somebody help me!

Hm, I never saw someone creating an Actor as a Subobject of another Actor.
I’m kinda sure that’s the core issue.

Can you try spawning the Actor with the default Spawn function in the BeginPlay of the second Actor, instead of its constructor?
Spawning in the Constructor could also work, though I’m not sure if GetWorld works there already.

Yes, it turns out I shouldn’t do that in the constructor, but spawn the actor inside BeginPlay, thanks! :slight_smile: