So, I am using datastores, and I am trying to make it so when someone steps onto a part, its value changes… How could I do this?
Here is the serverScript.
local data = game:GetService("DataStoreService")
local datastore1 = data:GetDataStore("DataStore1")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = leaderstats
local playerID = ("Player_".. player.UserId)
local data2
local succss, errormessage = pcall(function()
data2 = datastore1:GetAsync(playerID)
end)
if succss then
cash.Value = data2
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserID = "Player_".. player.UserId
local data3 = player.leaderstats.Cash.Value
local success, errormessage = pcall(function()
datastore1:SetAsync(playerUserID, data3)
end)
if success then
print("Booomer")
else
warn("Error fix.. debugg..")
end
end)
You chould do something like this, putting this script inside of your brick:
local brick = script.Parent
local canCollectCash = true --weather or not cash can be collected when the brick is being touched
--the code below runs when a player touches a brick because
--we're using the brick's .Touched event to call the function
brick.Touched:Connect(function(hit)
local player = game.Players:FindFirstChild(hit.Parent.Name)
if player and canCollectCash then
canCollectCash = false --when a player touches the part, set canCollectCash to false
local leaderstats = player:WaitForChild("leaderstats") --get the players cash value in the leaderstats
local cash = leaderstats:WaitForChild("Cash")
cash.Value = cash.Value + 1 --add one cash to the player's cash value
wait(1) -- wait a second before allowing cash to be able to be collected again
canCollectCash = true
end
end)
You can use a .Touched event, and when that specific user touches that part, it will increase their value by 1.
Here’s an example:
-- // Variables
local part = script.Parent
local player = game.Players.LocalPlayer
-- // Main Code
part.Touched:Connect(function()
player.leaderstats.cash.Value = player.leaderstats.cash.Value
end)
Additionally, you should never trust the client. Therefore I recommend using a RemoteEvent that can request this change to the server. The code above is made on the client, so it doesn’t save. Again, don’t trust the client when it comes to this.
No I got the saving part. I realized I was on a empty baseplate. But, it only saves sometimes . I want it to save no matter what. So using a remote event would not be good for a situation like this?