How can I create a constant (a node containing a value with one output) in Blueprint?
I don’t think you can… that feature is mainly a performance reducing one in C++, and blueprint doesn’t really work like that i guess…
You can make the variable private and create a BlueprintPure (enable const) that returns the variable. This way no other classes (even child classes) will be able to set that value to anything else.
To create a variable node, you can select and drag an input, and on the context menu which pops when you drop, select: “Promote to variable”.
I think I found best way to do constants using blueprints - Macro Library. Just create one and then in there you can create simple macro like this…
https://cdn.pbrd.co/images/9t1OTeCgn.png
And then use it whenever you want, no need for execution pins, acts like getter for a variable.
functional programming workaround for class dependent constants:
keep that function pure also.
try using the make literal node. of course this depends on type of value that you want to be a constant but you can use a make literal in a variety of situations. you could also use variables, addition nodes, and conversion string to int or something like that.
It’s not only a performance feature, but it’s also to save yourself from making mistakes. If it’s a constant value, you can’t accidentally write a different value to it. You can also instantly tell that it will only ever have one value. It’ll save you headaches later down the line when you go “But how come this value is changing?!” while debugging.
Incase anyone wants to expose a static constant from c++ to blueprint:
.h file:
UCLASS()
class MYPROJECT_API UMyCharacterStatic : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintPure)
static float GetMyConstant();
};
UCLASS()
class MYPROJECT_API AMyCharacter : public ACharacter {
GENERATED_BODY()
public:
static const float MY_CONSTANT;
);
.cpp file
const float AMyCharacter::MY_CONSTANT = 10.5f;
float UMyCharacterStatic::GetMyConstant(){ return AMyCharacter::MY_CONSTANT; }
This way you can use the static constant inside c++ and expose it to blueprints as well: