Can't get players job

I am trying to get the players current job and having some issues. I have the following in my code;

local PlayerData    = {}
ESX = nil

Citizen.CreateThread(function ()
    while ESX == nil do
		TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
		Citizen.Wait(0)
	end

    while ESX.GetPlayerData().job == nil do
        Citizen.Wait(10)
    end

    PlayerData = ESX.GetPlayerData()

end)

RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function(xPlayer)
  PlayerData = xPlayer
end)

RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
  PlayerData.job = job
  LSCMenu:showNotification(PlayerData.job.name)
end)

however when i try to use

Citizen.CreateThread(function()
if PlayerData.job.name == 'police' then
    --code here
end
end)

I get the error: attempt to index a nil value (field ‘job’)

am i missing anything or what am i doing wrong?

This should solve your situation… sorry for late answer but I just had the same problem but managed to fix it thanks to the esx_mechanicjob script:

ESX = nil

Citizen.CreateThread(function()
	while ESX == nil do
		TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
		Citizen.Wait(0)
	end

	while ESX.GetPlayerData().job == nil do
		Citizen.Wait(10)
	end

	ESX.PlayerData = ESX.GetPlayerData()
end)

RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function(xPlayer)
	ESX.PlayerData = xPlayer
end)

RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
	ESX.PlayerData.job = job
end)

Citizen.CreateThread(function()
	while true do
		Citizen.Wait(0)

		if ESX.PlayerData.job then
			ESX.ShowNotification(ESX.PlayerData.job.name)
		else
			ESX.ShowNotification("No job")
			Citizen.Wait(500)
		end
	end
end)
1 Like