How to manage UObject instances

Greg
Thu, 18 Aug 2022 09:17:09 +0000
C++

Hi,

i try to understand how to use allocation of Unreal object in Unreal 4.27.2.
if i create a class derived from UObject (UMyClass), and i put some instances of it in a TMap of an actor, it works.

UCLASS()
class DEMO_API UMyClass : public UObject
{
	GENERATED_BODY()
public:

	UPROPERTY(BlueprintReadOnly, Category = "My_Info")
	FString TestString;

	UMyClass();
};

UCLASS()
class DEMO_API AMyActor : public AActor
{
	GENERATED_BODY()
private:
	UPROPERTY(EditAnywhere, Category = MapExample)
	TMap<int, UMyClass*> mapTest;
...
}

void AMyActor::BeginPlay()
{
	Super::BeginPlay();

	mapTest.Add(21, NewObject<UMyClass>()  );
}

void AMyActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (mapTest.Num() > 0)
	{
		for (auto& entity : mapTest)
		{
			FString msg = FString::Printf(TEXT("AMyActor::Tick first: %d"), entity.Key);
			GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, msg);
		}
	}
}

But if i put my UMyClass in a class derived from UObject, it crashes

UCLASS()
class DEMO_API AMyActor : public AActor
{
	GENERATED_BODY()
private:
	UMyOtherClass*			 _Test;
...
}

void AMyActor::AMyActor()
{
	_Test = CreateDefaultSubobject<UMyOtherClass>("MyTest");
}

void AMyActor::BeginPlay()
{
	Super::BeginPlay();

	_Test->Init(this);
}

UCLASS()
class DEMO_API UMyOtherClass : public UObject
{
	GENERATED_BODY()

public:

	UPROPERTY(EditAnywhere, Category = MapExample)
	TMap<int, UMyClass*> mapTest;

	bool Init();
};


bool UMyOtherClass::Init()
{
	mapTest.Add(42, NewObject<UMyClass>());  // It crsh !!!!!

	return true;
}

I have tried to use my actor has parent in NewObject and it’s the same thing:

bool UMyOtherClass::Init(AMyActor* parent)
{
	mapTest.Add(42, NewObject<UMyClass>(parent));  // It crsh !!!!!

	return true;
}

How can i manage instances of a UObject in another UObject ?

3 posts - 3 participants