Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why will this function not run twice?

It runs through the first time perfectly fine, but if I want to click it a second time I cannot. Been trying to solve it for 10-15 minutes and even took a break from earlier to think about it but can't figure out why.

local blueCrystal = game.Workspace:WaitForChild("Blue_Crystal")
local blueClickDetector = blueCrystal.ClickDetector
local isBlueSpawned = true
local respawnTime = 2 --Incase you don't know it's minutes*60 = respawnTime


blueClickDetector.MouseClick:connect(function(player)
	if isBlueSpawned == true then
		local playerHumanoid = player.Character.Humanoid
		playerHumanoid.WalkSpeed = 40
		for i = 0, 1, .1 do
			wait()
			blueCrystal.Transparency = i
		end
		isBlueSpawned = false
		blueCrystal:Destroy()
		wait(respawnTime)
		local newCrystal = game.ReplicatedStorage.Blue_Crystal:Clone()
		newCrystal.Parent = game.Workspace
		blueCrystal = newCrystal
		blueClickDetector = newCrystal.ClickDetector
		print(blueClickDetector.Parent.Parent)
		isBlueSpawned = true
	end
end)


2 comments

0

the error is ranging from line 15-23, try moving the isBlueSpawned = true somewhere up

0

Well I tried to move it in between every line after wait, nothing changed. Ty for trying though

1 answer

✓ Accepted answer

Problem

The reason this function works only the first time through is because when the function is called, the new click detector inside of the cloned blue crystal does not have a listener function to respond to the MouseClicked event. Only the first one does.

Solution

Do not define the function as an anonymous one. Put it in a variable and connect the function to the MouseClick event every time the blue crystal is cloned.

local blueCrystal = game.Workspace:WaitForChild("Blue_Crystal")
local blueClickDetector = blueCrystal.ClickDetector
local isBlueSpawned = true

function onClicked(player)
	if isBlueSpawned == true then
        local playerHumanoid = player.Character.Humanoid
        playerHumanoid.WalkSpeed = 40
        for i = 0, 1, .1 do
            wait()
            blueCrystal.Transparency = i
        end
        isBlueSpawned = false
        blueCrystal:Destroy()
        wait(respawnTime)
        local newCrystal = game.ReplicatedStorage.Blue_Crystal:Clone()
        newCrystal.Parent = game.Workspace
        blueCrystal = newCrystal
        blueClickDetector = newCrystal.ClickDetector
		blueClickDetector.MouseClick:Connect(onClicked)
        print(blueClickDetector.Parent.Parent)
        isBlueSpawned = true
    end
end

blueClickDetector.MouseClick:Connect(onClicked)

This discussion is preserved as it was. New answers, comments, and votes are closed.