Hello helpers,
I am learning scripting still so please don't be too hard on me if there is a simple solution to this or if there is a better way.
I have this Datastore script that I followed from the tutorial here https://www.youtube.com/watch?v=FgcWmYhi7I8 (I understand pretty much everything in it so I didn't just copy and paste it..)
Basically when the player joins it checks if the player has data and if not it runs newData which is a table that is a template for the data that needs to be stored. The data is then stored to ServerData
How would I access for example "Cash" to change the value of it from another script?
Here is the code
--services
local Players = game:GetService("Players")
local DataService = game:GetService("DataStoreService")
local PlayerData = DataService:GetDataStore("PlayerData")
--variables
local ServerData = {}
local SavingFor = {}
--functions
local function newData() --template for what the data is
return {
Cash = 200,
tWood =150,
Stats = {
Speed = 16,
Jump = 50,
},
}
end
local function loadData(player)
local data
local Success, Error = pcall(function() data = PlayerData:GetAsync("data:"..player.UserId) end) -- if servers are down it will not break
if not Success then
warn(" Could not get data for "..player.Name)
return
end
if not data then -- if player is new (no data in pcall) the new data equals the new data template
data = newData()
end
ServerData[player] = data
end
local function saveData(player)
if not SavingFor[player] then
SavingFor[player] = true
if ServerData[player] then
local Success, Error = pcall(function() PlayerData:SetAsync("data:"..player.UserId, ServerData[player]) end)
if not Success then
warn("Data wasn't saved for"..player.Name.."!")
return
end
ServerData[player] = nil
end
SavingFor[player] = nil
end
end
Players.PlayerAdded:Connect(function(player)
loadData(player)
end)
Players.PlayerRemoving:Connect(function(player)
saveData(player)
end)
game:BindToClose(function()
for i,player in pairs (Players:GetChildren()) do
saveData(player)
end
end)
Thank you in advance

6 comments
But wouldn't that have to be done inside the same script as the datastore? I was wondering if it could be done from another script?
+= does not work
DataStores can be accessed from all scripts, if you do PlayerData:GetAsync(KEY) then it will return the table if all goes well, no matter what script it is.
local DataService = game:GetService("DataStoreService") local PlayerData = DataService:GetDataStore("PlayerData") game.Players.PlayerAdded:Connect(function(player) PlayerData:GetAsync("data:"..player.UserId) print(PlayerData.Cash) end) this dosen't work im getting cash is not a valid member of globaldatastore
No, you do local Data = PlayerData:GetAsync('data:'..player.UserId') print(Data.Cash)
Thank you!!