Skip to content

Commit

Permalink
fix(server/events): statebag handler for hunger/stress/thirst (#540)
Browse files Browse the repository at this point in the history
* feat(server/events): statebag handler for hunger/stress/thirst

* fix(server/events): add guard clause for infinite recursion

* fix(server/events): use thread to settle statebag for guard condition
  • Loading branch information
solareon authored Aug 20, 2024
1 parent e0de12b commit 6007cb9
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions server/events.lua
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,32 @@ RegisterNetEvent('QBCore:ToggleDuty', function()
player.Functions.SetJobDuty(true)
Notify(src, locale('info.on_duty'))
end
end)

---Syncs the player's hunger, thirst, and stress levels with the statebags
---@param bagName string
---@param meta 'hunger' | 'thirst' | 'stress'
---@param value number
local function playerStateBagCheck(bagName, meta, value)
if not value then return end
local plySrc = GetPlayerFromStateBagName(bagName)
if not plySrc then return end
CreateThread(function()
local player = QBX.Players[plySrc]
if not player then return end
if player.PlayerData.metadata[meta] == value and Player(plySrc).state[meta] == value then return end
player.Functions.SetMetaData(meta, value)
end)
end

AddStateBagChangeHandler('hunger', nil, function(bagName, _, value)
playerStateBagCheck(bagName, 'hunger', value)
end)

AddStateBagChangeHandler('thirst', nil, function(bagName, _, value)
playerStateBagCheck(bagName, 'thirst', value)
end)

AddStateBagChangeHandler('stress', nil, function(bagName, _, value)
playerStateBagCheck(bagName, 'stress', value)
end)

0 comments on commit 6007cb9

Please sign in to comment.