Well, I want the following dataStore to be saved if a value of the 2 IntValue changes, it really doesn’t work and I don’t know how to fix this
local players = game:GetService("Players")
local datastore = game:GetService("DataStoreService")
local SaveData = datastore:GetDataStore("Hunger&ThirstData")
players.PlayerAdded:connect(function(plr)
local Folder = Instance.new("Folder")
Folder.Name = "NeedsPlayerStats"
Folder.Parent = plr
local Hunger = Instance.new("IntValue")
Hunger.Name = "Hunger"
Hunger.Parent = Folder
Hunger.Value = SaveData:GetAsync(plr.UserId) or 100
local Thirst = Instance.new("IntValue")
Thirst.Name = "Thirst"
Thirst.Parent = Folder
Thirst.Value = SaveData:GetAsync(plr.UserId) or 100
if Hunger.Value.Changed or Thirst.Value.Changed then
print("Change")
SaveData:SetAsync(plr.UserId, Hunger.Value and Thirst.Value)
end
end)
You need to :Connect() the .Changed event to a function like so:
Hunger.Changed:Connect(function(value) --value is the IntValue's Value property, this is automatically passed in as a parameter
--Save data
end)
Also, you need to split the .Changed events up. You can call the same function within these connections like this:
Hunger.Changed:Connect(function(value)
--save function here
end)
Thirst.Changed:Connect(function(value)
--save function here
end)
Regardless of the code I posted above, you should almost never be saving data to a datastore whenever the value changes. Instead, save the values when the player leaves the games and at regular intervals. Datastores only allow a certain key to be updated once every 6 seconds so if these values are changing often it will cause issues.
To save player data when the player leaves the game you can instead do:
game.Players.PlayerRemoving:Connect(function(player)
--save function here
end)
As a final note, when saving multiple variables to a single datastore it’s useful to make a table of the variables and save the table instead. Below is an example of doing that and also an example of what a Save() function could look like in your scenario.
function Save(player)
local playerData = {
Hunger = player.NeedsPlayerStats.Hunger.Value;
Thirst = player.NeedsHungerStats.Thirst.Value;
}
SaveData:SetAsync(player.UserId, playerData)
end