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

Switching code from localscript to script caused it to stop working?

I have a bus game where if you are in the driver seat a GUI pops up where you can see a button that says headlights. It's a togglable button to turn the headlights on and off. I used to have the code in a local script, which worked, but then I realized that only the person who clicked it could see it (client-sided). I then copied the code over to a script and it stopped working...

Here's the code VV

local button = script.Parent
local light = game.Workspace.Headlights.Headlight1.SpotLight
local headlight = game.Workspace.Headlights.Headlight1
local light2 = game.Workspace.Headlights.Headlight2.SpotLight
local headlight2 = game.Workspace.Headlights.Headlight2
local toggled = false


local function onButtonActivated()
	if toggled == false then
		headlight.Material = 288
		light.Brightness = 1
		headlight2.Material = 288
		light2.Brightness = 1
		toggled = true
	else		
		headlight.Material = 256
		light.Brightness = 0
		headlight2.Material = 256
		light2.Brightness = 0
		toggled = false
	end
end
 
button.Activated:Connect(onButtonActivated)

1 answer

✓ Accepted answer

I added :WaitForChild() and :GetService() so that your script can wait for parts to load before proceeding to run. Also, you'll need a part with a ClickDetector for this code to work and this script must be a child of the button. If you want to make a GUI button pop up and run this script for the whole server to see, then you'll have to use a Remote Event or Remote Function.

local button = script.Parent
local ClickDetector = button:WaitForChild('ClickDetector')
local headlights = game:GetService('Workspace'):WaitForChild('Headlights')
local Headlight1 = headlights:WaitForChild('Headlight1')
local Headlight2 = headlights:WaitForChild('Headlight2')
local light = Headlight1:WaitForChild('SpotLight')
local light2 =  Headlight2:WaitForChild('SpotLight')
local toggled = false


local function onButtonActivated()
    if not toggled then
        Headlight1.Material = 288
        light.Brightness = 1
        Headlight2.Material = 288
        light2.Brightness = 1
        toggled = true
    else        
        Headlight1.Material = 256
        light.Brightness = 0
        Headlight2.Material = 256
        light2.Brightness = 0
        toggled = false
    end
end

ClickDetector.MouseClick:Connect(onButtonActivated)

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