Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

DataStore save only one team?

Asked by 5 years ago

I want to create prison team in game and script which will prevent prisoners from escape by re-join. I tested that on roblox 2 times and nothing happened. Script type is standard script and location is workspace. Here's the code:

game.Players.PlayerRemoving:connect(function(player)
    if player.TeamColor == BrickColor.new("Medium stone grey") then
    local datastore = game:GetService("DataStoreService"):GetDataStore(player.TeamColor)
datastore:SetAsync(player.TeamColor)
end
end)


game.Players.PlayerAdded:connect(function(player)
    local datastore = game:GetService("DataStoreService"):GetDataStore(player.TeamColor)
    player.TeamColor = datastore:GetAsync(player.TeamColor)
end)

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

First of all, you should be declaring your datastore variable outside of the functions. This will save memory, as you won't be creating a new one each time the function runs. Additionally, :connect() is deprecated. Use :Connect() instead. Now onto the big issue.

:SetAsync() requires two arguments: key, and value, respectively. You have the value (the player's TeamColor), but you're missing the key. When saving individual player's values, you should be using a unique key. This is typically the player's UserId, sometimes accompanied by a string value.

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

local DefaultTeamColor = BrickColor.new("Really red") --change this to what the default should be if no data has been previously saved.

game.Players.PlayerAdded:Connect(function(player)
   local key = "player_" .. player.UserId
   player.TeamColor = datastore:GetAsync(key) or DefaultTeamColor
end)

game.Players.PlayerRemoving:Connect(function(player)
   local key = "player_" .. player.UserId
   if player.TeamColor == BrickColor.new("Medium stone grey") then
      datastore:SetAsync(key,player.TeamColor)
   end
end)

Notice how I assigned a default value to the player's TeamColor if :GetAsync() returns nil. If we don't do this, the script will error if the returned data is nil.


Resources:

:SetAsync()


Accept and upvote if this helps!

Ad

Answer this question