Instancing custom object in constructor

I have a custom uobject class as such (simplified version):

UCLASS(DefaultToInstanced, Blueprintable, BlueprintType, EditInlineNew)
class MYPROJECT_API UMyObject : public UObject {

    GENERATED_BODY()

    public:
        UPROPERTY(EditAnywhere, BlueprintReadWrite)
        int32 MyValue = 10;

        UFUNCTION(BlueprintCallable)
        virtual void UpdateValue();
}

and I’d like to instance them & set their values in the constructor of my character

MyCharacter.h file

UCLASS()
class MYPROJECT_API AMyCharacter : public ACharacter {

   GENERATED_BODY()

   public:
       AMyCharacter();
   
       UPROPERTY(Instanced, VisibleAnywhere)
       UMyObject* MyObjectA;

       UPROPERTY(Instanced, VisibleAnywhere)
       UMyObject* MyObjectB;

       UPROPERTY(Instanced, VisibleAnywhere)
       UMyObject* MyObjectC;

       ...
};

MyCharacter.cpp file

AMyCharacter::AMyCharacter() {
    ...

    MyObjectA = CreateDefaultSubobject<UMyObject>(TEXT("My Object A"));
    MyObjectA.MyValue = 58;

    MyObjectB = CreateDefaultSubobject<UMyObject>(TEXT("My Object B"));
    MyObjectB.MyValue = 391;

    MyObjectC = CreateDefaultSubobject<UMyObject>(TEXT("My Object C"));
    MyObjectB.MyValue = 75;
}

Is this the right way to doing so? or will this cause any issues/ inconsistencies ?

Yes, that’s fine. The only thing you should watch out for is that the sub object names should not contain spaces. Something with that is known to cause problems with object paths.

1 Like

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