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

How can I make a local script enable/disable another local script?

Asked by 1 year ago

It is a simple question but I am unable to fine answer. For reference, I have two local scripts, one to enable/disable the other and the other is the script that actually does things. In my case, I have an X-Ray vision type thing but what I want to do is make it so that I can enable and disable it by running the script to enable/disable it if that makes sense? I know I need to use Remote Events and that but I do not know how to integrate it. This is the enable/disable script:

local uis = game:GetService("UserInputService")

uis.InputBegan:Connect(function(inp, processed)

    if processed then return end


    if inp.KeyCode == Enum.KeyCode.F then

        script.Parent["EyeOfX-RayVision"].Enabled = true
    end
end)

uis.InputEnded:Connect(function(inp)


    if inp.KeyCode == Enum.KeyCode.F then

        script.Parent["EyeOfX-RayVision"].Enabled = false
    end
end)

All help would be appreciated.

1 answer

Log in to vote
0
Answered by 1 year ago
Edited 1 year ago

Sadly, you cannot re-run the script once you re-enabled it. Instead, put the script inside the "enable/disable" script and make that script a function/thread.

For example: you have script 1 and 2. Script 1 prints "hi" in the Output every second, meanwhile Script 2 enables/disables Script 1 in order to play and stop the loop multiple times. Here's the thing: it doesn't work like that. You have to make Script 1 a function/thread inside Script 2 then run it.

Before:

--Script 1
while task.wait(1) do
    print("hi") --prints hi every 1 second
end

--Script 2
local Script1 = workspace.Script1

while task.wait(5) do
    Script1.Enabled = not Script1.Enabled --toggles Script1.Enabled true/false every 5 second
end

After:

--Script 2

local Script1 = coroutine.create(function() --creates a function/thread copy of Script 1
    while task.wait(1) do
        print("hi")
    end
end)

coroutine.resume(Script1) -- "enables" it
while task.wait(5) do
    local status = coroutine.status(Script1) -- gets its status as a string

    if status == "running" then -- if Script1 is "enabled"
        coroutine.close(Script1) -- this sets the thread status to dead or "disabled"
    elseif status == "dead" then -- if Script1 is "disabled"
        Script1 = coroutine.create(function() -- creates a new one
            while task.wait(1) do
                print("hi")
            end
        end)

        coroutine.resume(Script1) -- "re-enables" it
    end
end

Note: This is just an example. Don't copy-and-paste it directly to your script or it will error. Do this method on your own.

Hope this helped!

Learn more about coroutines

Ad

Answer this question