Hey everyone, I’m working on an inventory system using ModuleScripts, but I ran into an issue. When I change a table’s value on the server, the client still sees it as 0. Why is this happening, and how can I fix it?
Client
local InventoryModule = require(plr:WaitForChild("Inventory"))
while wait(1) do
for i, v in pairs(InventoryModule.Items) do
print(i .. " " .. v .. "x")
end
end
Server
local InventoryModule = require(plr:WaitForChild("Inventory"))
inventory.Items[item] = inventory.Items[item] + 1
Server and client while might share the same module script the data within does not replicate between security levels. If you have data in the module on client server will not see that change or if you change information in the module on server client won’t see those changes.
If you change the information inside the module on client another local script on your client will be able to see the change in data.
I’d recommend using remote events or remote functions to create the connection between server/client.
Heres kind of an example of what you’d do for server. Ideally client shouldn’t be sharing the same module as server but in the case they do it’d typically be set up differently through runservice or something where it’d separate the script from server/client though the data still won’t be shared.
local Inventory = {}
Inventory.Players = {}
function Inventory.addPlayer(Player)
if Inventory.Players[Player] then
return -- Player already added.
end
Inventory.Players[Player] = {
Items = {}
}
end
function Inventory.removePlayer(Player)
if not Inventory.Players[Player] then
return
end
Inventory.Players[Player] = nil
end
function Inventory:getInventory(Player)
if not Inventory.Players[Player] then
return nil -- Player doesn't exist or hasn't been added; could be joining or leaving
end
return Inventory.Players[Player]
end
function Inventory:Start()
requestInventory.OnServerInvoke = function(Player) -- Client sends invoke to server to get their inventory and server will either return the users inventory or nil depending on if they are still active or not.
return Inventory:getInventory(Player)
end
end
return Inventory