Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why will this function not run twice?

Asked by
F_lipe 135
6 years ago

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)


0
the error is ranging from line 15-23, try moving the isBlueSpawned = true somewhere up greatneil80 2647 — 6y
0
Well I tried to move it in between every line after wait, nothing changed. Ty for trying though F_lipe 135 — 6y

1 answer

Log in to vote
1
Answered by
RayCurse 1518 Moderation Voter
6 years ago
Edited 6 years ago

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)
Ad

Answer this question