Hi,
In short: how to prevent from loosing a pointer to data that is dynamically generated in OnConstruct() method? Pointer is NULL during gameplay, but holds a proper addres in editor.
This post looks big but I believe the content is very simple I guess it’s a beginner question I have that most of you knows the answer to. I was wondering if you could please explain how to proceed in cases like mine.
I have my custom class which currently doesn’t inherit from any UE4 classes:
class MyData
{
...
};
I have my custom actor based class that has a property of pointer to MyData:
class ... AMyActor : public AActor
{
...
MyData* pointer;
void OnConstruct(...)
{
pointer = new MyData();
}
};
As you can see dynamic creation of MyData instance takes place in OnConstruct(), which means that I already have the instance in UEditor, which is important to me.
Now, there is a problem: I noticed that when I launch a game, the pointer gets null’ified. I’m looking for a solution to prevent that.
I read about garbage collecting and stuff and I figured out some solutions. I’d be grateful to hear your opinions which way is better or if any of them is good at all.
Method 1 - Using FGCObject:
I add FGCObject to inheritance list of AMyActor class and mark the pointer with special method, like this:
class ... AMyActor : public AActor, **public FGCObject**
{
...
MyData* pointer;
void OnConstruct(...)
{
pointer = new MyData();
}
** void AddReferencedObjects(FReferenceCollector& Collector) override
{
Collector.AddReferencedObject(pointer);
}**
};
I’m not sure if mixing AActor and FGCObject together in the base of my actor class won’t cause any troubles… I already tried this and got some strange error messages during compilation, but I’m still fighting this. Not sure if this even prevents the pointer from being zeroed…
Method 2 - Using UOBject:
I add FGCObject to inheritance list of MyData class:
class MyData : **public UOBject**
{
...
};
And thanks to this, hopefully, I will be able to use UPROPERTY() above the declaration of my pointer:
class ... AMyActor : public AActor
{
...
**UPROPERTY()**
MyData* pointer;
void OnConstruct(...)
{
pointer =** NewObject**<MyData>();
}
};
I noticed that using UPROPERTY() prevents from losing pointer value, but it requires the pointer to be of one of UE4 specific types.
Method 3 - … i haven’t found yet … any suggestions what to look for?