I ran into a very confusing problem.
I have a character …
class ... ABaseCharacter : public ACharacter
… which has an inventory …
UPROPERTY( Replicated, VisibleAnywhere, BlueprintReadWrite, Category = "Inventory" )
UInventory* Inventory;
That UInventory is just inherited from UObject:
UCLASS(Transient)
class ... UInventory : public UObject
It contains a bunch of functions to Add, Remove and Get stuff and an Array
UPROPERTY()
TArray<class ABaseMeshActor*> Inventory;
In my PlayerController’s “BeginPlay” I populate the Inventory with some items:
ABaseMeshActor* Item;
Item = Cast<ABaseMeshActor>( GameMode->SpawnItemByName( Character, TEXT( "WeaponSword1" ) ) );
if ( Item )
Character->Inventory->Add( Item );
// ...
UE_LOG( LogTemp, Warning, TEXT( "Default Inventory spawned. %d" ), Character->Inventory->Num() );
The first time I start the editor and run the game, I see an output in the log window like that:
LogTemp:Warning: Default Inventory spawned. 4
LogTemp:Warning: Item "WeaponSword1" added to Quick Slot 1
LogTemp:Warning: Item "Shield1" linked to Quick Slot 1
LogTemp:Warning: Item "Bow1" added to Quick Slot 2
And everything is fine.
BUT … when I closed the game with ESC and ran it again, I got an access violation and the editor crashes. Rinse and repeat. First time it works. Second time it crashes, always. After a bit of wondering, adding some pointer checks here and there and outputting number of items in “Inventory” with the “Default inventory spawned” message, I saw that the array size actually increases with each session?!?
So every time I hit ESC and “Play” again, the Inventory size increases by 4 (the number of items I add) …
Fresh editor, Play …
LogTemp:Warning: Default Inventory spawned. 4
LogTemp:Warning: Item "WeaponSword1" added to Quick Slot 1
LogTemp:Warning: Item "Shield1" linked to Quick Slot 1
LogTemp:Warning: Item "Bow1" added to Quick Slot 2
… ESC … Play …
LogTemp:Warning: Default Inventory spawned. 8
LogTemp:Warning: ERROR: Inventory[0] is nullptr
… ESC … Play …
LogTemp:Warning: Default Inventory spawned. 12
LogTemp:Warning: ERROR: Inventory[0] is nullptr
I never told him to store anything?! Even tho it doesn’t make any sense (because you expect stuff to be 0, NULL, empty on program start …) I already tried “Inventory.Empty()” in the “UInventory” constructor, no change.
What is going on? Why is UE doing this?