Skip to content
The Chat Archive
gemini-2.5-flash-lite-preview-06-17-thinking· Google LMArena Human Preference 140K

this script randomly resets the timer please fix it: local Players =…

  1. User

    this script randomly resets the timer please fix it: local Players = game:GetService("Players") local ServerStorage = game:GetService("ServerStorage") local RunService = game:GetService("RunService")

    local GravityCoil = ServerStorage:WaitForChild("GravityCoil") local MinutesRequired = 15 local FriendsRequired = 5

    local playtimePart = workspace:WaitForChild("PlaytimeGiverPart") local billboard = playtimePart:WaitForChild("BillboardGui") local infoLabel = billboard:WaitForChild("InfoLabel") local timerLabel = billboard:WaitForChild("TimerLabel")

    -- Force positions & sizes to stack vertically infoLabel.AnchorPoint = Vector2.new(0, 0) infoLabel.Position = UDim2.new(0, 0, 0, 0) infoLabel.Size = UDim2.new(1, 0, 0.5, 0)

    timerLabel.AnchorPoint = Vector2.new(0, 0) timerLabel.Position = UDim2.new(0, 0, 0.5, 0) timerLabel.Size = UDim2.new(1, 0, 0.5, 0)

    -- Static instructions infoLabel.Text = "Play for 15 minutes or invite 5 friends for a surprise!" timerLabel.Text = ""

    -- Check invites local function hasInvitedEnoughFriends(player) local stats = player:FindFirstChild("leaderstats") if stats then local invites = stats:FindFirstChild("FriendsInvited") if invites and invites.Value >= FriendsRequired then return true end end return false end

    -- Give coil safely local function giveGravityCoil(player) if player.Backpack:FindFirstChild("GravityCoil") or (player.Character and player.Character:FindFirstChild("GravityCoil")) then return end local coil = GravityCoil:Clone() coil.Parent = player.Backpack end

    Players.PlayerAdded:Connect(function(player) local timeJoined = tick() local gotTool = false

    -- Check invites first
    if hasInvitedEnoughFriends(player) then
    	giveGravityCoil(player)
    	gotTool = true
    	timerLabel.Text = "You got the Gravity Coil!"
    end
    
    -- Update countdown always
    local connection
    connection = RunService.Heartbeat:Connect(function()
    	if not player.Parent then
    		connection:Disconnect()  -- Disconnect heartbeat if player leaves
    		return
    	end
    	if gotTool then
    		connection:Disconnect()  -- Disconnect heartbeat if tool already given
    		return
    	end
    
    	local timePlayed = tick() - timeJoined
    	local timeLeft = math.max(0, (MinutesRequired * 60) - timePlayed)
    
    	local minutes = math.floor(timeLeft / 60)
    	local seconds = math.floor(timeLeft % 60)
    
    	timerLabel.Text = string.format("Time Left: %d minutes, %d seconds", minutes, seconds)
    
    	if timeLeft <= 0 then
    		giveGravityCoil(player)
    		gotTool = true
    		timerLabel.Text = "You got the Gravity Coil!"
    		connection:Disconnect()  -- Disconnect heartbeat after giving tool
    	end
    end)
    

    end)

  2. Assistant

    Okay, let's analyze the script and figure out why the timer might be "resetting."

    The most common reasons a timer like this might appear to reset are:

    1. The timeJoined variable is reset: This shouldn't happen in your current script, as timeJoined is set once when PlayerAdded fires and is captured by the Heartbeat closure.
    2. The gotTool flag is reset: Similarly, gotTool is local to the PlayerAdded function scope and shouldn't be reset.
    3. The Heartbeat connection is disconnected and re-established: The connection is only created once per player. It's disconnected when the player leaves or when gotTool becomes true.
    4. Interference from other scripts: Another script might be modifying the timerLabel.Text, player.leaderstats, or even attempting to manipulate the timer logic itself.
    5. Server restarts or script reloading: If the server restarts or the script itself is reloaded/re-enabled, timeJoined would be reset for all players.
    6. tick() behavior: While unlikely, extremely rapid system clock changes (rare) could theoretically cause issues, but usually not a clean "reset."

    Looking at your code, the logic for gotTool and disconnecting the Heartbeat seems sound. The if gotTool then ... connection:Disconnect() ... check at the beginning of the Heartbeat function should prevent it from continuing once the tool is acquired.

    However, we can make the timer management slightly more robust and explicit by using a table to store player-specific timer data. This helps manage the state (like timeJoined, targetTime, and the connection) more cleanly, which can sometimes prevent subtle issues.

    Here's a revised version of your script that incorporates these improvements. This version uses targetTime instead of calculating timePlayed each frame, which is a slightly cleaner way to manage countdowns and might be marginally more resilient.

    -- Services
    local Players = game:GetService("Players")
    local ServerStorage = game:GetService("ServerStorage")
    local RunService = game:GetService("RunService")
    
    -- Configuration
    local GravityCoilAssetName = "GravityCoil" -- Ensure this matches the name in ServerStorage
    local MinutesRequired = 15
    local SecondsRequired = MinutesRequired * 60
    local FriendsRequired = 5
    
    -- UI Elements
    local playtimePart = workspace:WaitForChild("PlaytimeGiverPart")
    local billboard = playtimePart:WaitForChild("BillboardGui")
    local infoLabel = billboard:WaitForChild("InfoLabel")
    local timerLabel = billboard:WaitForChild("TimerLabel")
    
    -- Style UI Elements (Optional, but good practice to keep)
    infoLabel.AnchorPoint = Vector2.new(0, 0)
    infoLabel.Position = UDim2.new(0, 0, 0, 0)
    infoLabel.Size = UDim2.new(1, 0, 0.5, 0)
    
    timerLabel.AnchorPoint = Vector2.new(0, 0)
    timerLabel.Position = UDim2.new(0, 0, 0.5, 0)
    timerLabel.Size = UDim2.new(1, 0, 0.5, 0)
    
    -- Static instructions
    infoLabel.Text = string.format("Play for %d minutes or invite %d friends for a surprise!", MinutesRequired, FriendsRequired)
    timerLabel.Text = ""
    
    -- Store player timer data and connections
    -- Structure: { [player] = { targetTime = number, connection = RBXScriptConnection, gotTool = boolean } }
    local playerTimers = {}
    
    -- Load the GravityCoil tool from ServerStorage
    local GravityCoilTool = ServerStorage:WaitForChild(GravityCoilAssetName)
    
    -- Function to check if a player has invited enough friends
    local function hasInvitedEnoughFriends(player)
    	local stats = player:FindFirstChild("leaderstats")
    	if stats then
    		local invites = stats:FindFirstChild("FriendsInvited")
    		-- Ensure the value exists and is a number before comparing
    		if invites and typeof(invites.Value) == "number" and invites.Value >= FriendsRequired then
    			return true
    		end
    	end
    	return false
    end
    
    -- Function to safely give the GravityCoil tool to a player
    local function giveGravityCoil(player)
    	-- Check if player is valid and still exists
    	if not player or not player.Parent then return end
    
    	local backpack = player:FindFirstChild("Backpack")
    	local character = player.Character
    
    	-- Check if player already has the tool (in backpack or equipped)
    	local hasToolInBackpack = backpack and backpack:FindFirstChild(GravityCoilAssetName)
    	local isToolEquipped = character and character:FindFirstChild(GravityCoilAssetName)
    
    	if hasToolInBackpack or isToolEquipped then
    		-- print(player.Name .. " already has the Gravity Coil.")
    		return -- Player already has the tool
    	end
    
    	-- Clone and parent the tool
    	local coilClone = GravityCoilTool:Clone()
    	if backpack then
    		coilClone.Parent = backpack
    		-- print("Gave Gravity Coil to " .. player.Name .. " via Backpack.")
    	end
    end
    
    -- Function to update the timer display and check conditions
    local function updatePlayerTimer(player)
    	local timerData = playerTimers[player]
    	if not timerData then return end -- Should not happen if managed correctly
    
    	local currentTime = tick()
    	local timeLeft = math.max(0, timerData.targetTime - currentTime)
    
    	local minutes = math.floor(timeLeft / 60)
    	local seconds = math.floor(timeLeft % 60)
    
    	-- Update the timer label text
    	timerLabel.Text = string.format("Time Left: %d min, %d sec", minutes, seconds)
    
    	-- Check if the time limit has been reached
    	if timeLeft <= 0 then
    		if not timerData.gotTool then -- Only proceed if tool hasn't been given yet
    			giveGravityCoil(player)
    			timerData.gotTool = true -- Mark tool as given
    			timerLabel.Text = "You got the Gravity Coil!"
    
    			-- Disconnect the timer for this player
    			if timerData.connection then
    				timerData.connection:Disconnect()
    				timerData.connection = nil -- Clear the connection reference
    			end
    			-- Clean up player's timer data after they receive the tool
    			playerTimers[player] = nil
    			-- print("Timer finished and disconnected for:", player.Name)
    		end
    	end
    end
    
    -- Function to start the timer logic for a specific player
    local function startPlayerTimer(player)
    	-- Clean up any existing timer data for this player if they rejoin quickly or script reloads
    	if playerTimers[player] then
    		if playerTimers[player].connection then
    			playerTimers[player].connection:Disconnect()
    		end
    		playerTimers[player] = nil
    	end
    
    	local timeJoined = tick()
    	local targetTime = timeJoined + SecondsRequired
    	local gotTool = false
    
    	-- 1. Check invite condition first
    	if hasInvitedEnoughFriends(player) then
    		giveGravityCoil(player)
    		gotTool = true
    		timerLabel.Text = "You got the Gravity Coil!"
    		-- print("Gave Gravity Coil to " .. player.Name .. " via invite.")
    	end
    
    	-- Store initial player state
    	playerTimers[player] = {
    		targetTime = targetTime,
    		connection = nil, -- Will be assigned the actual connection object later
    		gotTool = gotTool
    	}
    
    	-- 2. If tool not given via invite, start the Heartbeat timer
    	if not gotTool then
    		local heartbeatConnection = RunService.Heartbeat:Connect(function()
    			-- Check if player still exists and timer is still relevant
    			local currentPlayer = Players:FindFirstChild(player.Name) -- Re-check player's presence
    
    			-- If player left or timer data is missing, disconnect and clean up
    			if not currentPlayer or not playerTimers[currentPlayer] then
    				if playerTimers[player] and playerTimers[player].connection then
    					playerTimers[player].connection:Disconnect()
    				end
    				playerTimers[player] = nil -- Remove data
    				-- print("Heartbeat disconnected (player left or data cleared) for:", player.Name)
    				return
    			end
    
    			-- Check if the tool was obtained by another means (e.g., invite check already ran)
    			-- or if the timer logic itself has already given the tool in a previous tick
    			local timerData = playerTimers[currentPlayer]
    			if timerData.gotTool then
    				-- If gotTool is true, disconnect and clean up
    				if timerData.connection then
    					timerData.connection:Disconnect()
    					playerTimers[currentPlayer] = nil -- Remove data
    				end
    				-- print("Heartbeat stopped (already got tool) for:", currentPlayer.Name)
    				return
    			end
    
    			-- Update the timer display and check if time is up
    			updatePlayerTimer(currentPlayer)
    		end)
    
    		-- Assign the connection to the player's data
    		playerTimers[player].connection = heartbeatConnection
    		-- print("Timer started for:", player.Name)
    	else
    		-- If tool was given via invite, remove timer data immediately as no timer is needed
    		playerTimers[player] = nil
    		-- print("Invite condition met, no timer needed for:", player.Name)
    	end
    end
    
    -- Connect the PlayerAdded event to start the timer for new players
    Players.PlayerAdded:Connect(startPlayerTimer)
    
    -- Connect the PlayerRemoving event to clean up timer data when a player leaves
    Players.PlayerRemoving:Connect(function(player)
    	if playerTimers[player] then
    		if playerTimers[player].connection then
    			playerTimers[player].connection:Disconnect() -- Ensure connection is cleaned up
    		end
    		playerTimers[player] = nil -- Remove player's timer data
    		-- print("Cleaned up timer data for leaving player:", player.Name)
    	end
    end)
    
    -- Handle players who might already be in the game when the script starts
    for _, player in ipairs(Players:GetPlayers()) do
    	startPlayerTimer(player)
    end
    

    Key Changes and Improvements:

    1. playerTimers Table: A table playerTimers is introduced to store essential data for each player (targetTime, connection, gotTool). This makes managing player states more organized and prevents potential conflicts if the script were reloaded or if players join/leave rapidly.
    2. targetTime Calculation: Instead of calculating timePlayed relative to timeJoined every frame, we calculate a targetTime (timeJoined + SecondsRequired) once. The timer then checks targetTime - currentTime. This is functionally similar but can be slightly cleaner.
    3. Explicit Connection Management: The Heartbeat connection is explicitly stored in playerTimers[player].connection and is disconnected when the player leaves (PlayerRemoving) or when the tool is successfully given.
    4. Robust gotTool Check: The gotTool flag is checked more carefully within the Heartbeat loop to ensure the timer stops immediately and cleanly once the tool is acquired, whether via invites or time expiring.
    5. Player Existence Check: Added a Players:FindFirstChild(player.Name) check within the Heartbeat loop. While player.Parent check is usually sufficient, this adds an extra layer of safety in case the player object itself is somehow invalidated.
    6. Initial Player Handling: The script now includes a loop to call startPlayerTimer for any players already in the game when the script first runs.
    7. Error Handling/Debugging Prints (Commented Out): Added print statements (commented out) that you can uncomment to help debug if the issue persists. They can show when timers start, stop, or tools are given.
    8. Asset Name Variable: Made the GravityCoilAssetName a variable for easier modification if you rename the tool.

    How to Use:

    1. Place the script: Make sure this script is a Server Script located in ServerScriptService. This is crucial for it to run correctly and manage player data server-side.
    2. Check Tool Name: Ensure the tool in ServerStorage is exactly named "GravityCoil" (or update GravityCoilAssetName in the script).
    3. Check Leaderstats: Ensure players have a leaderstats folder with a FriendsInvited IntValue or NumberValue.
    4. Test: Join the game and test the timer and invite functionality.

    If the timer still seems to reset after implementing this improved version, the cause is likely external:

    • Another script interfering: Look for scripts that might be modifying timerLabel.Text, leaderstats, or interacting with player tools.
    • Server instability: Frequent server restarts or crashes could cause the script to reload and reset timers.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.