Search code examples
c++oopobjectconstructorunreal-engine4

Create UObject from another class with constructor


I have a class, describing some object with properties, e.g. inventory item. And along with default constructor, I need parametrized constructor, to create items with certain set of parameters, for example, size)

UCLASS()
class xxx_API UItem : public UObject
{
    GENERATED_BODY()
public:
    UItem();
    ~UItem();
    UItem(int _size);

    UPROPERTY(BlueprintReadOnly, Category = "Parameters")
        int size = 0;
};

And I have another class, which I want to serve as container for pre defined items, so I can have references to it from other places of the game.

UCLASS()
class xxxx_API UItemsContainer : public UObject
{
    GENERATED_BODY()
public:
    UItemsContainer();
    ~UItemsContainer();

    UItem SomeItem = UItem(100);
};

So I can at the begiining of game create this item container

ItemsContainer = NewObject<UItemsContainer>();

And then add it to some item collection of certain entity like this

TArray<UItem*> CharacterItems = {};
CharacterItems.Add(&ItemsContainer.SomeItem);

Since items are fixed and will not change during game, I dont want to create specific object for each of them, and just have references to container entries.

Though on compilation I get error, that I try to access private members of UItem class. Though, it's constructor is public and all properties are public. I think that there is something in UClass, that dont allow me to use constructor that way, since I can do this with objects, that are not UObject. But I need it to be UObject, to be usable in blueprints. And I dont know how to call non-default constructor in other way. Probably I can create default object with NewObject, and then initialize it and store in array, but looks like there will be too much code and complication. Any suggestions please?


Solution

  • Because C++ has been stylized in Unreal, e.g. auto generated source file of UItem is in the directory:

    MyProj\Intermediate\Build\Win64\UE4Editor\Inc\MyProj\Item.generated.h
    

    You can open this source, the copy-constructor of UItem has been shadowed, and UItem SomeItem = UItem(); would trigger copy-constructor, so you will get a compilation error that try to access private members of UItem class.

    enter image description here

    In Unreal, you must invoke NewObject when creating UObject, e.g.

    SomeItemPtr = NewObject<UItem>(Outer);
    

    If you want to pass parameters on creating UObject, you can define a specific function

    void UItem::SetParams(int Size)
    {
        //initiation ...
    }
    

    e.g.

    UItemsContainer::AddItem(int ItemSize)
    {
        SomeItemPtr = NewObject<UItem>(this);
        SomeItemPtr->SetParams(ItemSize);
    }