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).
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.
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
And of course needed to change the UPROPERTY like that