目录
- UCLASS(BlueprintType,Blueprintable)
- class DESIGNPATTERNS_API USingletonObject:public UObject{
- GENERATED_BODY()
- public:
- UFUNCTION(BlueprintCallable)
- static USingletonObject* GetSinletonObjectIns();
-
- UFUNCTION(BlueprintCallable)
- void SetValue(int32 NewValue);
-
- UFUNCTION(BlueprintCallable)
- int32 GetValue();
-
- private:
- static USingletonObject* SingletonObject;
- int32 IntValue;
- };
-
- USingletonObject* USingletonObject::SingletonObject=nullptr;
-
- USingletonObject* USingletonObject::GetSinletonObjectIns(){
- if(SingletonObject==nullptr){
- SingletonObject=NewObject
(); - }
- return SinletonObject;
- }
-
- void USingletonObject::SetValue(int32 NewValue)
- {
- IntValue = NewValue;
- }
-
- int32 USingletonObject::GetValue()
- {
- UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" Value = %d"), IntValue);
- return IntValue;
- }
继承 UObject 创建单例类
Project Settings->Engine->General settings->Game Singleton Class 设置为自定义的单例类。会自动生成与销毁
把它当成全局常量来用,不建议运行中修改其中的变量数据
单例类代码,修改
- USingletonObject* USingletonObject::GetSingletonObjectIns()
- {
- if (SingletonObject == nullptr) // 也可以判断 GEngine
- {
- SingletonObject = Cast
(GEngine->GameSingleton); - }
- return SingletonObject;
- }