Static Variables in a UObject?

Is it possible to have an exposed static variable in a UObject child class?

The thing is I have lots of variables inside my classes that are shared and won’t differ in the instances of that class. So I could use a descriptor class to hold all the shared properties and reference it from the original class, but since it would be a 1:1 relation, I wouldn’t really gain anything by it and only complicate things. Static variables would make much more sense. Is there a way?

I don’t believe there are any special rules against static variables in UE4. It’s not an API issue, it’s a C++ feature:

.h
UCLASS()
class PROJECT_API MyClass : public UObject
{
     GENERATED_BODY()

 public:
     static int s_value;
};

.cpp
int MyClass::s_value = 1;
1 Like

Ok, but what if I want to expose the variable to be used and edited in the editor and its sub-editors (like persona)? I wasn’t able to use UPROPERTY() with a static variable…

Oh, I see what you mean. Sorry about that. No, a static UPROPERTY won’t work. Maybe a singleton?

Top answer from here:

Another good place to put globals is in a GameSingleton. If you set GameSingletonClassName to something in DefaultEngine.ini (or Project Settings → Engine → General settings) it will create an instance of that object for you. You can get then get to it from the variable GameSingleton on UEngine. On Fortnite we set up a game singleton, and then added something to our kismet library to get it on demand. If you subclass public UBlueprintFunctionLibrary, those functions will be available from any blueprint. It creates exactly one game singleton ever, so it’s a good place to put data references that are global across your entire game. You can make that Singleton Class point at any blueprint you may want, and then you can set variables on that as needed.