Code is erroring

image

local part = script.Parent
local connection = part.TouchEnded:Connect(function(hit)

--sound
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://9120936385"
sound.Volume = 1 
sound.Looped = false
sound.Parent = script.Parent
--sound

local lightpart = workspace.Lamp.Light
local spotlight = workspace.Lamp.Light.SpotLight

local lamp2_part = workspace.Lamp2.Light
local lamp2_light = workspace.Lamp2.Light.PointLight

local celling_light1 = workspace.Ceiling_Light.BeamBase.Beam
local celling_light2 = workspace.Ceiling_Light.BeamBase.SpotLight
local celling_light3 = workspace.Ceiling_Light.Specks.ParticleEmitter
local celling_light4 = workspace.Ceiling_Light.base
local celling_light5 = workspace.Ceiling_Light.lightbase


part.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid then
		sound:Play()
		celling_light1.Brightness = 1
		celling_light2.Brightness = 4
		celling_light3.Brightness = 1
		spotlight.Brightness = 1
		lamp2_light.Brightness = 1
		celling_light1.LightEmission = 0
		celling_light4.Transparency = 0
		celling_light5.Transparency = 0
			
		connection:Disconnect()
	end
end)

do

local connection = part.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid then
		sound:Play()
		celling_light1.Brightness = 1
		celling_light2.Brightness = 4
		celling_light3.Brightness = 1
		spotlight.Brightness = 1
		lamp2_light.Brightness = 1
		celling_light1.LightEmission = 0
		celling_light4.Transparency = 0
		celling_light5.Transparency = 0
			
		connection:Disconnect()
	end
end)
1 Like

Adding onto this solution…

You cannot do this (for example):

local connection = someEvent:Connect(function()
	connection:Disconnect()
end)

It would be nearly the same as doing this:

local number = number + 1

( ^ Which will obviously not work, because the 2nd “number” cannot “see” the number variable.)

Instead, do this:

local connection = nil

connection = someEvent:Connect(function()
	connection:Disconnect()
end)

This is nearly the same as doing this:

local number = 0
number = number + 1

( ^ Which will work because now the 2nd line is able to add 1 to the number variable because it can “see” it.)

Sorry this is hard to explain, but I hope you get the idea.

1 Like

I deleted the Disconnect code and wrote an easier code instead.

script.Enabled = false

Oh, well. You know what they say: “If it works, it works.” :skull:

Just going to say now that you should get more accustomed to not disabling scripts to disconnect an event.

1 Like

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