Object property is not valid when in blueprint child class

I have a character class called APerson_Character and an UObject class called UInventory.
The APerson_Character class has a property called “Inventory” of UInventory with default value of a new instance of an object, like the code below.

UCLASS()
class PROJECT1_API APerson_Character : public ACharacter
{
	GENERATED_BODY()
//
// Some code here
//
public:
	UPROPERTY(BlueprintReadOnly)
	UInventory* Inventory = NewObject<UInventory>(this, UInventory::StaticClass(), FName("Inventory"));
};

I also have a blueprint called APerson_CharacterBP, that inherits APerson_Character C++ class.

If I instantiante a character of APerson_Character, everything runs ok.
However, if I instantiate a character of APerson_CharacterBP, the property “Inventory” is not valid (it’s null).

Am I doing something wrong?

try:

UInventory* Inventory = NewObject<UInventory>();

Thanks for the answer, but the problem remains…

in the header just define the variable:

UPROPERTY(BlueprintReadWrite)
	UInventory* Inventory; 

in the Cpp initialize it in BeginPlay:

void APerson_Character::BeginPlay()
{
	Super::BeginPlay();
	Inventory = NewObject<UInventory>();
}

and if you want to access/check from blueprint child in the beginplay just add a delay in the blueprint BeginPlay.

Blueprints BeginPlay runs Before C++ BeginPlay

I thought doing like you suggested, but it wouldn’t be ideal.

When a player joins the game, I spawn a character programatically like this:

void AInGame_GameMode::PostLogin(APlayerController* NewPlayer)
{
	Super::PostLogin(NewPlayer);
	if (AInGame_GameState* InGame_GameState = GetGameState<AInGame_GameState>())
	{
		InGame_GameState->SpawnPerson(NewPlayer);
		Cast<AInGame_PlayerController>(NewPlayer)->SetInputModeGameOnly();
		// Here, I want to get the spawned character and load its inventory, hunger, thirsty, money etc. But the "Inventory" property is null.
	}
}

I need to access the inventory property just after I spawned the character, so I need do instantiate the UInventory object at the APerson_Character constructor.

Actually you can initialize in the C++ contructor without any problems…you can try and check (in C++!) and you will have a valid NewObject.

But it seems takes a ‘while’ to validate the object in the BP layer.

1 Like

I got the solution.

The blueprint “Inventory” property was set to null. I just needed to change it to the default instance of “UInventory” instantiated at contructor of the C++ class.

APerson_Character::APerson_Character()
{
	//
	// Some code...
	//

	// Instantiate the new object of UInventory.
	Inventory = CreateDefaultSubobject<UInventory>(FName("Inventory"));
}

At the details tab, in editor, I needed to click to set the default value of “Inventory” property, like that

image

And of course needed to change the UPROPERTY like that

	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly)
	UInventory* Inventory;
2 Likes