Hi, I am working on a game and I am trying to save a Value that is inside a part, that value is going to be displayed on a SurfaceGui. example:
For more context, whenever you touch a certain part it adds 1 to the value. And then I have a script inside the SurfaceGui that updates the text to show the value.
local touches = script.Parent.Parent.Parent.Parent.Touches
local text = script.Parent
touches.Changed:Connect(function()
text.Text = ""..touches.Value
end)
This is what it looks like in explorer (sorry if it’s messy)
(if you’re wondering, the datastore script in the explorer screenshot is blank)
But anyways, I am not good with DataStores and I don’t know how to code this, so if you know something or want to just point me in the right direction than go ahead and reply, I am going to try everything. Thanks
DataStores aren’t necessary for this unless you’re hoping to store the value across servers; simply use a variable here:
local clicks = 0
script.Parent.Touched:connect(function()
clicks = clicks+1
script.Parent.SurfaceGui.TextLabel.Text = clicks -- edit this to work with your naming
end)
If you hope to access this variable through multiple scripts, use the _G module:
local DSS = game:GetService("DataStoreService")
local DS = DSS:GetDataStore("YourDataStoreName")
Then saving and getting your data:
-- saving the data:
DS:SetAsync(key, data)
-- getting the data:
local data = DS:GetAsync(key)
It’s also highly recommended to wrap your :SetAsync and :GetAsync in a pcall() to prevent errors when DataStores are down:
-- saving data using a pcall
local success, message = pcall(function()
DS:SetAsync(key, data)
end)
if success then
print("Data Saved")
else
warn(message)
end
-- getting data using a pcall
local data
local success, message = pcall(function()
data = DS:GetAsync(key)
end)
if success then
if data then
-- data found
else
-- new player to the game
end
else
warn(message)
end
This may seem confusing, so I highly recommend watching the tutorials i posted above