I have a system where a player is given an inventory when they join the game. Then, a local script that gets this inventory from the server using a remote event. However, sometimes when I test the game, the inventory is nil and nothing is transferred to the player - other times it is not nil and the inventory data is transferred. I don't really know how to fix this.
This is the function to get a player's inventory (the inventory is stored on the server)
function RetrieveInv(player) wait(InventoryModule:GetInventory(player):GetContents()) -- this should (intheory) wait for the inventory to exist Event:FireClient(player, InventoryModule:GetInventory(player):GetContents()) -- send inventory to client end
Sometimes, the fireclient code runs, and fails because it is nil, other times it runs but an empty table is sent to the client. A lot of the time everything works though.
This is the local script that prints out the inventory
local invData function setupInv() Event:FireServer() wait(invData) print(Player.Name .. "'s Items:") if invData ~= nil then for i, item in pairs(invData)do print("Name:" .. i .. "\nAmount: " .. item.Amount .. "\nType: " .. item.Content.ItemClass) end end end function updateInv(newInv) invData = newInv end Event.OnClientEvent:Connect(updateInv) setupInv()
I know it's to do with concurrency - but I don't know how to force the game to wait for the inventory to exist before it sends anything to the client.
Adding an if statement to check if it is not nil works, but sometimes nothing is sent over, the local script stops trying to get data and the output is empty.
You can use a BoolValue which you set to true when the inventory system loaded. Then, in the code you can check if its loaded or not, and if it's not, wait for it to load using the Wait method of events like BoolValue.Changed:Wait()
(Changed only fires when the value changes and not other properties)
Also, as a side note, the server should not get the inventory data from the client. A hacker can change the data sent to the server, making it unreliable. Instead, you should store the inventory data on the server, and the client can get a personal copy for themselves to display on an inventory UI but not have the server use any inventory data on the client.