Search code examples
luaroblox

The door data is not saved in Roblox


I wrote a door save system. That is, if the user previously bought them, then when re-entering the game, they must be open. My code works, but the door doesn't save at all.

-- DoorsDataStore
-- Save Stats Doors
local opend = false
local datastorage = game:GetService("DataStoreService")
local isitopen_1 = datastorage:GetDataStore("Door")

game.Players.PlayerAdded:Connect(function(player)
    local boolValueDoors = Instance.new("Folder")
    boolValueDoors.Name = "BoolValueDoors"
    boolValueDoors.Parent = player
    
    local door_1 = Instance.new("BoolValue")
    door_1.Parent = boolValueDoors
    door_1.Name = "BoolValueDoor_1"
    door_1.Value = isitopen_1:GetAsync(player.UserId)  
    print("True or False")
    print(player.BoolValueDoor_1.Value)
end)

game.Players.PlayerRemoving:Connect(function(player)
    
    local success, erromsg = pcall(function()
        isitopen_1:SetAsync(player.UserId, player.BoolValueDoor_1.Value)
    end)
    
    if erromsg then
        warn("Error")
    end
end)
-- TouchDoor
script.Parent.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChild("Humanoid")
    if (humanoid ~= nil) then
        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        if player.leaderstats.Coins.Value >= script.Parent.Price.Value then
            player.leaderstats.Coins.Value -= script.Parent.Price.Value
            player.leaderstats.Level.Value += 1
            script.Parent:Destroy()
            player.BoolValueDoors.BoolValueDoor_1.Value = true
            print("Save Door")
        end
    end
end)        

I tried writing this code in different ways, in different versions, tried through validation. My code still doesn't do what I want.


Solution

  • There are multiple possible problems I see:

    1. SetAsync takes a string as the first argument, you are giving it a number value. To fix this use tostring(player.UserId)

    2. When the player first joins, the value will be set to nil, because there is no data in the datastore under the UserId, and nil is not a boolean.

    I’m not sure if these are actual issues and I currently cannot check if these are real problems because I’m not on my computer but they may be something you want to change. Also it would be nice to know if you encountered any errors when executing the code.

    You should also make trigger a remote event that opens the door on the clientside in the PlayerAdded function if the value is true.