Static variables in BP?

Hi!
The way I managed to use static variables in Blueprints is through C++.
You can declare a static variable in a C++ UCLASS, and getter/setter UFUNCTIONs for it.
Then, you can have your Blueprint parented to this C++ UCLASS. The Blueprint should be able to call the setter and getter in order to respectively modify and access the static variable, which will be shared among all instances of the Blueprint.

I see this as 50% solution, 50% workaround (it is not Blueprint-only and not necessarily flexible).

Here is a basic example with additions for a UCLASS deriving from AActor:

////////////// MyActor.h //////////////

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"

UCLASS()
class TESTPROJECT_API AMyActor : public AActor
{
	[...]

	// the static variable
	static int Counter;

	// setter, callable from Blueprint
	UFUNCTION(BlueprintCallable)
		void SetStaticCounter(int InCounterValue);

	// getter, callable from Blueprint (and pure)
	UFUNCTION(BlueprintPure)
		const int GetStaticCounter();    

    [...]
};


////////////// MyActor.cpp //////////////

#include "MyActor.h"

// set value so the variable has a known value :)
int AMyActor::Counter = 0;

[...]

void AMyActor::SetStaticCounter(int InCounterValue)
{
	Counter = InValue;
}

const int AMyActor::GetStaticCounter()
{
	return Counter;
}

[...]
1 Like