Detect variable value changes?


Is it somehow possible to detect if a value of my variable has changed?

if my float health; value changes something should happen automatically.

For example, in umg I can bind a variable to my progress bar, which automatically updates if the value changes.

Any ideas?

No C++ does not support that, there hacks to do so like create your own type and use operator overrides so you can detect = usage, but it’s something that would need to build from ground up in APIs. For example when you cast you type back to float* you won’t be able to detect changes anymore so entire engine would need to support your type. The prefred way in UE4 is to make variable private or protected and make set and get functions for it and change variable this way, the code from get and set function would be exectured on each use. You can see this theme in most of UE4 APIs

In case of UMG, you passing a pointer to variable (float*), which is not value state but memory address to variable which can be accessed from pointer in any time. UMG… or rather Slate that powers it, is hardware accelerated and it renders like a game on each frame, when it renders it grabs current state of variable from pointer he have, so there is no event it just takes current state of variable when drawing. Slate also support grabing values from function pointers, you point to function and object (like timer or delegate) and Slate will call function to get return value from it and display it, it using type called TAttribute to support static values, pointers and function pointers in same time:

1 Like

yeah i know that c++ doesn’t support it.

ok,i thought the binding works somehow else. thank you for your answer

For status bar the pointer solution sound good, if you use it exactly the same format, and you don’t need any calculations with it.

But my solution would be making it a private variable, and make a function change it, like ChangeVariableTo(float to); and calculations and events that you have to make and call should be put in there. (Also, don’t forget to replace the codes where you already change your variable directly)

If you use Blueprints you can make the UE do it for you, if you change the variable’s replication to RepNotify. It automatically creates a function called OnRep_Variable that is called every time the variable is changed.

If your variable is a UPROPERTY, use PostEditChangeProperty to respond every time a property changes. For example code, see How do I use PostEditChangeProperty?.