I am trying to send a random number from the server side to the client side.
It doesnt work on the Client side because all clients should have the same random number.
Here is my code which unfortunately does not work, does anyone know why?
Hey there!
As I see, many people confuse local and global variables, same with server-side and client-side.
serverRandom on Server-Side does indeed have this random number. On Client-Side it’s a local variable, which means its trapped in arg in Event Handler.
To get this value from server, you should use print(serverRandom) in event and not outside of it.
As for clientRandom. It doesn’t have enough time for it to be updated. Client=>Server=>Client takes up more time than you think. At least few ms(miliseconds) in best case. Create Thread and wait some time or stick with arg in your event.
Unfortunately, I am not yet that familiar with CreateThreads. It’s my first script haha.
I have understood why it outputs nil on the client side, obviously.
Unfortunately, using print(serverRandom) in the event doesn’t help me. I only wrote the output to visualise which numbers are currently being output during testing.
Regarding the point create thread. I have now written the following, which causes my game to crash
clientRandom = 0
TriggerServerEvent('ServerRdm')
Citizen.CreateThread( function ()
while true do
RegisterNetEvent('ServerRdm')
AddEventHandler('ServerRdm', function(serverRandom)
clientRandom = serverRandom
Citizen.Wait(5000)
end)
end
end)
print(clientRandom)
Threads are simple thing(if you need help with understanding something in lua other than this discussion then dm me). Here is the Client-side code
local clientRandom = 0
TriggerServerEvent('ServerRdm')
RegisterNetEvent('ServerRdm') -- register once and it will work just fine
AddEventHandler('ServerRdm', function(serverRandom)
clientRandom = serverRandom -- overriding local clientRandom
print(clientRandom, serverRandom) -- same thing
end)
print(clientRandom) -- will return 0
CreateThread(function()
print(clientRandom) -- will return 0
print(serverRandom) -- will return nil
Wait(500) -- delay between execution
print(clientRandom) -- will return value from server-side
end)