Last active
February 17, 2025 18:14
-
-
Save draobrehtom/2216e8996a6ba9c350facb3cbb2f9e26 to your computer and use it in GitHub Desktop.
Example of state bags usage in FiveM (Siren system for vehicles)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| local sirens = {} | |
| local function playSiren(entity) | |
| -- Prevent from playing siren twice | |
| if sirens[tostring(entity)] then return false end | |
| print('Play siren', 'State', Entity(entity).state['siren']) | |
| sirens[tostring(entity)] = true | |
| return true | |
| end | |
| local function stopSiren(entity) | |
| sirens[tostring(entity)] = nil | |
| print('Stop siren', 'State', Entity(entity).state['siren']) | |
| end | |
| AddStateBagChangeHandler('siren', nil, function(bagName, key, value, _, rep) | |
| -- Handle only siren 'on' state | |
| if value ~= true then return end | |
| -- Get entity (stable alternative for GetEntityFromStateBagName(bagName)) | |
| local netId, _ = string.gsub(bagName, 'entity:', '') | |
| netId = tonumber(netId) | |
| local timeoutAt = GetGameTimer() + 1500 | |
| while not NetworkDoesEntityExistWithNetworkId(netId) do | |
| Wait(0) | |
| if GetGameTimer() >= timeoutAt then | |
| return print('Timeout, entity network doesnt exist', netId) | |
| end | |
| end | |
| local entity = NetworkGetEntityFromNetworkId(netId) | |
| -- Ensure entity exists | |
| if not DoesEntityExist(entity) then return print('Entity doesnt exist', entity) end | |
| -- Ensure handler executed only once (local player replication) | |
| local amOwner = NetworkGetEntityOwner(entity) == PlayerId() | |
| if amOwner and replicated then return end | |
| -- Ensure entity has the state assigned | |
| while Entity(entity).state['siren'] ~= true do Wait(0) end | |
| -- Play siren | |
| if playSiren(entity) then | |
| -- Wait entity exists and while siren is enabled | |
| while DoesEntityExist(entity) and Entity(entity).state['siren'] == true do | |
| Wait(200) | |
| end | |
| -- Stop siren | |
| stopSiren(entity) | |
| end | |
| end) | |
| RegisterCommand('sirenon', function() | |
| local vehicle = GetVehiclePedIsIn(PlayerPedId()) | |
| if not DoesEntityExist(vehicle) then | |
| return | |
| end | |
| Entity(vehicle).state:set('siren', true, true) | |
| end, false) | |
| RegisterCommand('sirenoff', function() | |
| local vehicle = GetVehiclePedIsIn(PlayerPedId()) | |
| if not DoesEntityExist(vehicle) then | |
| return | |
| end | |
| Entity(vehicle).state:set('siren', false, true) | |
| end, false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment