How to manage UObject instances

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 :frowning:

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 ?

It shouldn’t have anything to do with where the variable is. For your _Test variable you’re missing the UPROPERTY macro. This allows reflection and therefore the garbage collector to know it’s referenced and not get rid of it.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.