Static instance will be pending kill after 1 min in Tick

Hi, in Tick I use the “ErrData” in instance.

128552-3.png

But after 1 minute since I run the program(I try many times and it happens around 1 min). The Instance is pending kill from the function.

And here are my h/cpp files. I dont know why the instance is pending kill. Is there anything wrong with the “static”?

I think your UCommonDataMgr was collected by the engine.

All UObject will be managed by the engine. You need to see this about the UObject garbage collection.
Any ‘useless’ UObject will be collected by the engine.

Solution 1 (recommended)

Make a UCommonDataMgr member in the UGameInstance, like this:

/// MyGameInstance.h file
#pragma once

#include "Engine/GameInstance.h"
#include "MyGameInstance.generated.h"

UCLASS()
class UMyGameInstance : public UGameInstance
{
    GENERATED_BODY()

public:
    UMyGameInstance();

private:
    UPROPERTY()
    class UCommonDataMgr* CommonDataMgr;

public:
    UFUNCTION(BlueprintPure, meta = (WorldContext = "WorldContextObject"), Category = "MyGameInstance")
    static class UCommonDataMgr* GetCommonDataMgr(UObject* WorldContextObject);
};

// MyGameInstance.cpp file
#include "YourProjectPrivate.h"
#include "MyGameInstance.h"
#include "CommonDataMgr.h"

UMyGameInstance::UMyGameInstance()
    : CommonDataMgr(NULL)
{
    //
}

UCommonDataMgr* UMyGameInstance::GetCommonDataMgr(UObject* WorldContextObject)
{
    check(WorldContextObject);
    UWorld* World = WorldContextObject->GetWorld();
    UMyGameInstance* MyGameInstance = Cast<UMyGameInstance>(World->GetGameInstance());
    if (MyGameInstance && !MyGameInstance->CommonDataMgr)
    {
        MyGameInstance->CommonDataMgr = NewObject<UCommonDataMgr>(MyGameInstance);
    }
    check(CommonDataMgr);
    return CommonDataMgr;
}

And you need to set the default game instance to UMyGameInstance in your project.

Solution 2

You can call UObject->AddToRoot(), like this:

if (NULL == _instance2)
{
    _instance2 = NewObject<UCommonDataMgr>();
    _instance2->AddToRoot();
}

Solution 3 (not recommended)

Don’t inherit from UObject. Just handle by yourself.

Please don’t capture the code into the picture.