Hey guys, I am in my first week of learning the Unreal Engine and so far I am working only with the editor and with blueprints, so I’m not coding anything (I have decent programming experience, but only in Java)
I have a player (Pawn blueprint, since I don’t actually need a Character) which has a “energy” variable. The energy is regenerating automatically over time. I am doing this in the “Event Tick” node of my player, because I want to have a steady regeneration rate independent of the framerate. The logic in the Event Tick node is basically:
if (at least X ticks passed since last energy regeneration)
-> get current energy value
-> calculate energy += 1%
-> set new energy value
There’s also an event in my game where I want to set the player’s energy to 0. For test purposes I just trigger this on a key press. So I have a “Enhanced Input Action” node where I have the logic:
Set health = 0
Now from my general programming knowledge, I guess there’s already potential race conditions here, because the “Event Tick” node and the input action node could be executed concurrently, I assume?
Meaning that we can have this sequence in logic:
[Logic in event tick node]
get current energy value, e.g. 60% right now
calculate energy += 1% = 61%
[Now the logic from the triggered input action node interferes: set energy = 0%]
[Logic continues in event tick node]
set new energy value = 61% because this was already calulated before
So the event that was supposed to set the energy to 0 would get overwritten, and the energy would immediately go back from 0% to 61%, instead of starting again at 1%.
Now I know in “real programming” you would have to synchronize access to shared variables, so my question is: Can I do this without C++ code in the Blueprints? Are there thread-safe variables, or some other means of synchronizing such access?
I tried to define my own function in a separate “Energy Manager” Actor Blueprint which holds the energy variable, and has a boolean to lock concurrent access. But this is not the locking you usually would have, where a process would wait until the resource is free. With my solution I can only have a branch on the boolean and if it’s false I can just ignore the event. But this means I couldn’T process multiple events when they appear concurrently. I then thought of just collecting all incoming changes to the energy value in some queue and process them one after another. But again here I would need a thread-safe queue, right?
Right now I hit a dead end pretty much. I wouldn’t know how to program a functioning game when I cannot prevent such race conditions.
Thank you very much!