Script doesn't seem to do anything after being disabled

Hi! Today I am experiencing an issue with this script. It works fine and all, does it’s job.

The issue I am having is that whenever the script is disabled by another script after the currentlevel is deleted, and this script is enabled it does not work and generate another number.

Why is it like this? Am I simply doing something wrong?

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LevelCompleted = ReplicatedStorage:WaitForChild("LevelCompleted")

while true do
    local levelfolder = game.ReplicatedStorage.Levels

    local generate = math.random(1, 2)

    if generate == 1 then
        local level1clone = levelfolder.Level1:Clone()
        level1clone.Parent = game.Workspace
        level1clone.Name = "CurrentLevel"
        print("Level1 Picked")
        script.Disabled = true
		return
    end

    if generate == 2 then
        local level2clone = levelfolder.Level2:Clone()
        level2clone.Parent = game.Workspace
        level2clone.Name = "CurrentLevel"
        print("Level2 Picked")
        script.Disabled = true
        return
    end
end

LevelCompleted.OnServerEvent:Connect(function()
    script.Disabled = false
end)
1 Like

Do not use toggling the Disabled property to control when scripts run. Use BindableEvents and their .Wait event to have the script wait for a trigger from your other script.

I recommend that instead of disabling and re-enabling the script, you turn picking your level into a function, and simply run that fuction when the remote event is fired.

On a side note, unrelated to the post, but you can actually pick a random level out of a folder instead of picking a number and assigning that number to a level.

To do this:

local levels = game.ReplicatedStorage.Levels:GetChildren()
local levelClone = levels[math.random(1, #levels)]:Clone()

Hope this helps :grin:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.