Switching (creating) components by GameInstance variable

Hello there!

I took a course in Unreal Engine [ C++ ] but seems not enough to do some tricks.

I want to create a custom component for an actor based on a “global” variable which I thought best place for holding it was GameInstance.

When creating the actor, a switch sentence is called then if that variable is ‘0’ then component A is created and attached, otherwise, component B is created and attached.

Seems easy but I miss lot of concepts.

First of all, if I try to get my custom GameMode or GameInstance inside the constructor of the actor, this is crushing Unreal (after searching and debugging I think it’s because those objects are not created yet…). But I can retrieve them in the ACustomActor::BeginPlay() function, so I have been able to attach them this way.

The question here is if this is the correct way to do this because I think it is not. But what I would like to learn is why GameInstance or GameMode is not created before an actor “creation” / spawn ??

I feel like missing something.

Is the behaivour this one?:
GameInstance calls for a GameMode, then spawn actors inside the map. I would like to know who is in charge of load maps, and who is spawning actors.

Thanks for the support!!

Keep the good work :slight_smile:

It is not safe to call any functions that depend on the World being in any known state inside the Constructor of anything.

You can use BeginPlay to do that.

1 Like

^ that. Also another thing to realize is class constructors fire at other times than loading a game map, including when: (1) populating the content browser, and (2) opening the map in editor. I don’t believe GameInstance will even exist in those cases.

You can query world type like this:

#include "Engine/World.h"

if (GetWorld() && GetWorld()->WorldType == EWorldType::Editor || GetWorld()->WorldType == EWorldType::EditorPreview)
 // do something

All world types: EWorldType::Type | Unreal Engine Documentation