hours is not valid member of Folder "Players.trynotazies.leaderstats"

Viewed 27

For some reason when I am trying to save the data for my leader stats script it says not a valid member. Any help would be appreciated right now. This is for a game I am making on Roblox and hoping for it to grow popular

Here is the code:

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DataStore")

game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local hours = Instance.new("IntValue")
    hours.Name = "Hours"
    hours.Value = 0
    hours.Parent = leaderstats

    local Sleep_Tokens = Instance.new("IntValue")
    Sleep_Tokens.Name = "Sleep Tokens"
    Sleep_Tokens.Value = 0
    Sleep_Tokens.Parent = leaderstats

    local data
    local data2
    local success, errormessage = pcall(function()
        data = DataStore:GetAsync(player.UserId.."-hours")
        data2 = DataStore:GetAsync(player.UserId.."-sleeptokens")
    end)

    if success then
        hours.Value = data
        Sleep_Tokens.Value = data2
    else
        print("Had an error while retrieving player data")
        warn(errormessage)
    end
end)

game.Players.PlayerRemoving:Connect(function(player)
    local success, errormessage = pcall(function()
        DataStore:SetAsync(player.UserId.."-hours",player.leaderstats.hours.Value)
        DataStore:SetAsync(player.UserId.."-sleeptokens",player.leaderstats.Sleep_Tokens.Value)
    end)

    if success then
        print("Player Data Saved")
    else
        print("Had an error while saving player data")
        warn(errormessage)
    end
end)
1 Answers

The error is telling you that hours isn't a child of the player's leaderstats. This is because object names are case-sensitive, and when you created the IntValue, you named it Hours :

    local hours = Instance.new("IntValue")
    hours.Name = "Hours"
    hours.Value = 0
    hours.Parent = leaderstats

When you are saving the data, you either need to index the leaderstats using the proper name Hours or change the IntValue's Name to be hours. You'll run into the same issue with Sleep_Tokens.

Try this :

        DataStore:SetAsync(player.UserId.."-hours", player.leaderstats.Hours.Value)
        DataStore:SetAsync(player.UserId.."-sleeptokens", player.leaderstats["Sleep Tokens"].Value)
Related