I tried to learn some datastore with Gemini and other DevForum users. I tried to improve my code with Gemini. I understand almost everything in the code(But i feel ashamed cuz its mostly made by Ai. Im not using it for full code but learning something new).
If you have some advices(Or whatever), tell me.
local DatastoreService = game:GetService("DataStoreService")
local PlayerTixData = DatastoreService:GetDataStore("PlayerTixData")
local players = game:GetService("Players")
local PlayerData = {}
local part = workspace:WaitForChild("Part")
local function givetix(plr, amount)
local data = PlayerData[plr.UserId]
if not data then return end
data.Tix += amount
print("U got" .. amount .. "! You have " .. data.Tix .. " now.")
end
players.PlayerAdded:Connect(function(plr)
local Key = tostring(plr.UserId)
local success, plrdata = pcall(function()
return PlayerTixData:GetAsync(Key)
end)
if success then
PlayerData[plr.UserId] = plrdata or {Tix = 50}
print("You have " .. PlayerData[plr.UserId].Tix .. " tix.")
else
warn("Nevermind....")
end
end)
local function SaveData(plr)
local key = tostring(plr.UserId)
local PlaceToSave = PlayerData[plr.UserId]
if PlaceToSave then
local success, err = pcall(function()
PlayerTixData:SetAsync(key, PlaceToSave)
end)
if success then
print("Data saved successfully!")
else
warn("Failed to save data: " .. err)
end
PlayerData[plr.UserId] = nil
end
end
players.PlayerRemoving:Connect(SaveData)
game:BindToClose(function()
for _, plr in pairs(players:GetPlayers()) do
SaveData(plr)
end
end)
part.Touched:Connect(function(hit)
local plr = players:GetPlayerFromCharacter(hit.Parent)
if not plr then return end
givetix(plr, 50)
end)
This code is working well(I didnt add cooldown thing)
(Im still beginner btw)
Have a nice day/Night! : D