Instantiating a UObject in runtime

Hi. I have created a dataset system that consists of pure UObjects in a hierachy.
So GI has an objA which has an objB and a set of multiple objC. (It’s much more complex than this, but just for giving an oveview).

When i want to create another objC, i try using:
UObjC* obj = NewObject();

But in game it returns something completely off, or crashes entirely. I have looked around but can’t seem to find how to create an UObject through c++ only. Posts talk about components, actors etc. which confuses me. I just want to create an instance of a UObject.

Atm, i am using BlueprintImplementableEvent, where i create and add them. However to do this i must each time make a BP_objC child class and do it in BP so i can “Construct object of class” and set it as variable, which is a poor solution.

What is the right way to create an instance of a UObject?
Hope you can help :slight_smile: Thanks in advance.

UPROPERTY()
UObjB* objB;

UPROPERTY()
TArray<UObjC*> objCs;
objB = NewObject<UObjB>();
UObjC* obj = NewObject<UObjC>();
objCs.Emplace(obj);

It is important to store your objects in UPROPERTY members to avoid garbage collection sweeps.

I make it like this now and it seem to work :slight_smile: Thanks :slight_smile:

UDataStatDay* UDataStatistics::CreateNewDayStat(int32 day)
{
    UDataStatDay* obj = NewObject<UDataStatDay>(this);
    obj->GameData = GameData;
    DayStats.Add(day, obj);

    return obj;
}

Before i had this, where it created it, but only created one

UDataStatDay* UDataStatistics::CreateNewDayStat(int32 day)
{
    UDataStatDay* obj = NewObject<UDataStatDay>(this, UDataStatDay::StaticClass());
    obj->GameData = GameData;
    DayStats.Add(day, obj);

    return obj;
}

And tried this which which didn’t work before, but it didn’t seem to work, and it could eaily crash as well. But now it works.

UDataStatDay* UDataStatistics::CreateNewDayStat(int32 day)
{
    UDataStatDay* obj = NewObject<UDataStatDay>();
    obj->GameData = GameData;
    DayStats.Add(day, obj);

    return obj;
}

So first of all, thanks :slight_smile: It’s seems to work now.

I have been fighting his for 2 days now, so don’t feel more clever than before.
Should this method ALWAYS work, or why do some add “this” and this “StaticClass” thing. Are there specific situations where i need to add this?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.