Hello everyone, so I was updating my treasure game, where you should find them, and in the previous versions of the game, I was having a separate scripts with collecting function in every treasure model. But, I’ve understood that, this is not the best idea, and I’ve rewrote every script into the one main server script using for do.
But I have a bug, that, whenever a player touches the hitbox of the treasure, it should call a function that adds a found value and adds a value into the table using Profile Service. And it should also fire an event. But in my script, it’s firstly adds a found value and a value into the table. But, it fires an event in 3-5 seconds before it actually giving it to the player. (The event that script is firing, it’s an event with a GUI that pops out)
Here is the Server Script:
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CollectionService = game:GetService("CollectionService")
local Remotes = ReplicatedStorage:WaitForChild("Remotes")
local collect, taken = Remotes["Events"].TreasureCollect, Remotes["Events"].AlreadyTaken
local ServerScriptService = game:GetService("ServerScriptService")
local DataFolder = ReplicatedStorage:WaitForChild("Common"):WaitForChild("Data")
local Data = require(ServerScriptService:WaitForChild("Server"):WaitForChild("Data"):WaitForChild("Handler"))
local treasures: Folder? = workspace.Main:WaitForChild("Treasures")
local hitboxes = treasures:GetDescendants()
local playerDebounces = {}
for _, hitbox: Part in pairs(hitboxes) do
if hitbox:IsA("Part") and hitbox.Name == "Hitbox" then
hitbox.Touched:Connect(function(hit)
local character: Model? = hit.Parent
local client: Player = Players:GetPlayerFromCharacter(character)
if not client then return end
if playerDebounces[client] then
warn("Debounce active, exiting early.")
return
end
playerDebounces[client] = true
task.delay(0.1, function()
playerDebounces[client] = false
end)
local treasure: Model? = hitbox.Parent
if not treasure then return end
local hasTag = CollectionService:HasTag(treasure, client.UserId.."_Collected")
if hasTag then taken:FireClient(client) return end
CollectionService:AddTag(treasure, client.UserId.."_Collected")
task.spawn(function()
local clientTreasures: {}? = Data:GetTreasures(client)
local alreadyCollected = table.find(clientTreasures, treasure.Name)
if alreadyCollected then taken:FireClient(client) return end
local function spaceOut(str: string)
return str:gsub("(%l)(%u)", "%1 %2")
end
local text = spaceOut(treasure.Name)
collect:FireClient(client, text, treasure.Coloring.Main.Color, treasure.Difficulty.Value)
Data:Update(client, "Found", function(old)
return (tonumber(old) or 0) + 1
end)
Data:AddTreasure(client, treasure.Name)
warn("Treasure collected successfully.")
end)
end)
end
end
If someone can help me, that would be really appreciated!
Thanks.