'How to get PlayerGUI from a Server Script?

I am working on an inventory system and and now i need to make it save, but when trying to save it prints this in the output

PlayerGui is not a valid member of Player "Players.RidhoMBLR"

local function save(player)
    local invTable = {}

    for i, v in pairs(player.PlayerGui.ScreenGui.Inventory.InvFrame:GetChildren()) do
        if v:IsA("TextButton") then
            table.insert(invTable, v)
        end
    end

   dataStore:SetAsync(player.UserId, invTable)
end

players.PlayerRemoving:Connect(save)


Solution 1:[1]

While you are accessing the path to the PlayerGui correctly, it is probably not replicated to the server (ie, it's existence is only observable on the client in LocalScripts).

So you will likely need to use a LocalScript to pull all of the relevant information out of the UI, and communicate it up to the server using a RemoteEvent. So move your code to a LocalScript :

local players = game.Players
local saveEvent = game.ReplicatedStorage.RemoteEvent -- find your RemoteEvent here

local function save(player)
    -- only tell the server about it if we are the one leaving
    if player ~= players.LocalPlayer then
        return
    end

    -- get information about the inventory
    local inventory = player.PlayerGui.ScreenGui.Inventory.InvFrame:GetChildren()
    local invTable = {}
    for i, v in ipairs(intentory) do
        if v:IsA("TextButton") then
            -- grab the text out of each button
            table.insert(invTable, v.Text)
        end
    end

   -- tell the server about our inventory
   saveEvent:FireServer(invTable)
end

players.PlayerRemoving:Connect(save)

Then in a server Script, listen for when clients fire the event and save their data then :

local saveEvent = game.ReplicatedStorage.RemoteEvent -- find that same RemoteEvent

-- listen for when players report that they are leaving
saveEvent.OnServerEvent:Connect(function(player, inventoryTable)
    -- save their information
    dataStore:SetAsync(player.UserId, inventoryTable)
end)

Solution 2:[2]

So basically you can't access a player's PlayerGui through the server. PlayerGui is replicated locally for each client, hence in order to interact with a Player's Gui I'd recommend using RemoteEvents. By using Remote events you'd be sending a signal to the client which can then by picked up by a LocalScript. On the local script you can then fire another RemoteEvent back to the server with a list of all the items which you can then SetAsync on the server.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kylaaa
Solution 2 YellowBannanaRBX