To best illustrate my issue - I have a class that I created that is a UObject called UCrosshairs. I created this as a utility class because I do not like monolithic massive main classes, and my character class was getting huge - so I broke it out into smaller sub-classes that control certain aspects of the character to better keep the class sizes smaller.
It was defined in my character h file:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true"))
class UCrosshairs* UICrosshairs;
Then in the constructor of my character object I would instantiate my helper classes:
UICrosshairs = NewObject<UCrosshairs>();
Initialize is a method on UICrosshairs that takes in the character reference.
I could then pass in pointer to this object and everything was fine. Fast forward a few months and today I’m in my character class Blueprint.
I make a change to my camera boom in blueprint and that at that point breaks my code forever until I rollback my change.
Tracing the issue I discover that after the constructor finishes and I try to use UICrosshairs - it is now null automagically. Revert the blueprint change and it all works fine again.
I finally got this to work by placing the instantiation in BeginPlay instead of the constructor.
So question #1 is:
Why do I have to put this call in the BeginPlay portion instead of the constructor? What causes a UPROPERTY to suddenly go null after the constructor when it worked fine before and I made a change to a blueprint’s camera property?
I have a scene component I’m instantiating:
ReloadHandSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("HandSceneComponent"));
Now this one HAS to be done in the constructor. If you try to put this code in BeginPlay, you get a fatal error.
Why do some objects need instantiated in a constructor and others BeginPlay?
I’m coming from a lengthy 20+year C# background, but my C++ is intermediate. The fact that we have several ways to create objects in Unreal is something I’m trying to get tighter with and understand these apparent gotcha pitfalls that are a black hole of development time trying to figure out.