Download

How to create Instanced uproperty subobjects

I have been trying to get the following behaviour

Create an ActorComponent with an as UPROPERTY marked UObject contining some editable property.
I have encountered several issues with this and the best way to achieve this was to make the UPROPERTY Instanced.
Now I still have the issue of creating the UObject in the ActorComponent. Either the UObject get’s not created at all when adding the ActorComponent to a Blueprint Actor or the properties of the UObject are reset to default (the defaults in the UObject c++ implementation not the one set in the actor blueprint, or the UObject is not created at all when adding the component to the actor in a blueprint.

Here is my example to make this more understandable:

The ActorComponent:

Header:



#pragma once

#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "ExampleActorComponent.generated.h"


UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class PROJECTROGUE_API UExampleActorComponent : public UActorComponent
{
GENERATED_BODY()

public:
// Sets default values for this component's properties
UExampleActorComponent();

public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Instanced)
class UExampleObject* ExampleObject;
};


CPP:



#include "ExampleActorComponent.h"

// Sets default values for this component's properties
UExampleActorComponent::UExampleActorComponent()
{
// not creating DefaultSubobject of ExampleObject here

PrimaryComponentTick.bCanEverTick = true;
}



the UObject:
.
Header:



#pragma once

#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "ExampleObject.generated.h"

UCLASS(ClassGroup = (Custom), DefaultToInstanced, EditInlineNew)
class PROJECTROGUE_API UExampleObject : public UObject
{
GENERATED_BODY()

protected:
UPROPERTY(EditDefaultsOnly)
float DefaultNumber = 1.0f;

UPROPERTY(VisibleAnywhere)
float VisibleNumber = 1.0f;
};


CPP
is empty.

I want to be able to add ExampleActorComponent to an actor blueprint and change the value of DefaultNumber affecting all my actor instances but I can’t get this behavior to work correctly.

The question is now: where do I add the creation of the ExampleObject in the ExampleActorComponent, if I add it in the constructor the values of the DefaultNumber in ExampleObject will reset on play to 1.0 even when changet in an actor blueprint.

I have tried to find a function in ActorComponent that is called after the serialized properties are loaded to check if the ExampleObject already exists and only create one if there is none, but I’m not sure if this is the right approach to the problem.

Thanks for any advice or help with this issue.