Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why doesn't this DataStore script work?

I'm trying to save the value when players leaves, and then load that data when a player joins. How am I supposed to do this?


DataStore = game:GetService("DataStoreService")

game.Players.PlayerRemoving:connect(function(plr)
	local value = plr.PlayerGui:WaitForChild("RankGui").Rank.Rank
    local key = "Rank_" .. plr.userId
    DataStore:SetAsync(key,value.Value)
end)

local DataStore = game:GetService("DataStoreService"):GetGlobalDataStore("Rank")

game.Players.PlayerAdded:connect(function(Player)
    local PlayerKey = "Rank_" .. Player.userId

    local leaderstats = Instance.new("IntValue", Player)
    leaderstats.Name = "leaderstats"

    local Rank = Instance.new("StringValue", leaderstats)
    Rank.Name = "Rank"
  	if DataStore:GetAsync(PlayerKey) ~= nil then
	Rank.Value = DataStore:GetAsync(PlayerKey)
else
	Rank.Value = "Civilian"
end
end)

Where it says, GetGlobalDataStore, how does it know that it's called "Rank"? I never defined it. However, data never loads anyways. Also, whenever i leave, I end up with Civilian.

2 comments

0

i dont understand it.

1 answer

✓ Accepted answer

I think you forgot the method :GetGlobalDataStore() in the PlayerRemoving function (line 6). I have a way to fix your script:

DataStore = game:GetService("DataStoreService"):GetGlobalDataStore("Rank")

game.Players.PlayerRemoving:connect(function(plr)
    local value = plr.PlayerGui:WaitForChild("RankGui").Rank.Rank
    local key = "Rank_" .. plr.UserId -- "userId" is deprecated!
    DataStore:SetAsync(key,value.Value)
end)

local DataStore = game:GetService("DataStoreService"):GetGlobalDataStore("Rank")

game.Players.PlayerAdded:connect(function(Player)
    --Variables
    local PlayerKey = "Rank_" .. Player.UserId -- Use capital "U" for "UserId."

    local leaderstats = Instance.new("IntValue", Player)
    leaderstats.Name = "leaderstats"

    local Rank = Instance.new("StringValue", leaderstats)
    Rank.Name = "Rank"
    Rank.Value = "Civilian" -- Add a preferred value for Rank (Useful later)

     local GetSaved = DataStore:GetAsync(PlayerKey) -- I would rather do it this way starting here, but you can do it your way.
	if GetSaved then
	    Rank.Value = GetSaved[1]
	else
	    local toSave = {Rank.Value} -- This will set the "Rank" to "Civillain" in the DataStore.
	    DataStore:SetAsync(PlayerKey, toSave)
	end
end)

I hope this would work for you. If you have any problems, comment down below. Good luck!

2 comments

0

What does dss mean? line 27. is it DataStore variable?

0

yes your datastore variable Its edited now

This discussion is preserved as it was. New answers, comments, and votes are closed.