To sync particle effects between all clients in FiveM scripting, you will need to use server events to create and manage the particle effects for each client. Here's an example using Lua for both server and client side:
Server side:
First, create a new file server.lua in your resource folder if it does not already exist.
Then, add this code to the server-side script:
RegisterNetEvent('sync:spawnParticle')
AddEventHandler('sync:spawnParticle', function(effect, pos)
local _source = source
TriggerClientEvent('sync:displayParticle', -1, effect, pos, _source)
end)
This code creates an event handler for the sync:spawnParticle event. When the event is triggered, it will also trigger the sync:displayParticle client event for all connected clients.
Client-side:
In your client-side script, for example client.lua, you will add the following code to handle the sync:displayParticle event:
RegisterNetEvent('sync:displayParticle')
AddEventHandler('sync:displayParticle', function(effect, pos, _source)
local particleDictionary = "scr_rcbarry2"
local particleName = effect
RequestPTFXAsset(particleDictionary)
while not HasPTFXAssetLoaded(particleDictionary) do
Citizen.Wait(0)
end
local sCoords = vector3(pos.x, pos.y, pos.z)
local particleEffect = StartParticleFxLoopedAtCoord(particleName, sCoords.x, sCoords.y, sCoords.z, 0.0, 0.0, 0.0, 1.0, false, false, false, false)
-- Set a timer to stop the particle effect after some time.
Citizen.CreateThread(function()
Citizen.Wait(5000) -- Adjust this value to change the duration of the effect.
StopParticleFxLooped(particleEffect, false)
end)
end)
This code handles the sync:displayParticle event and creates the particle effect at the specified position for each connected client. Replace the particleDictionary and particleName variables with the appropriate names for the effect you want to use.
Triggering the particle effect:
You can trigger the particle effect from either the client or the server-side, depending on when you want to create the particle effect.
Here is an example of triggering the particle effect from the client-side:
local positionOfEffect = GetEntityCoords(PlayerPedId())
TriggerServerEvent('sync:spawnParticle', "scr_bike_business", positionOfEffect)
Make sure to replace "scr_bike_business" with the name of the particle effect desired.
Now, all clients will see the same particle effect in the synced position. Note that this example does not take streaming range into consideration. Clients will see the particle effect regardless of the distance to the effect. You can optimize this by using the client's distance to the effect and handle it accordingly.