How to make this function fire only once?

This is quite different from the other posts I have read.

This is a script I got from the Developer Hub:

local part = script.Parent
 
-- Add a light
local pointLight = Instance.new("PointLight", part)
pointLight.Brightness = 0
pointLight.Range = 12
 
local touchNo = 0
local function blink()
	-- Advance touchNo to tell other blink() calls to stop early
	touchNo = touchNo + 1
	-- Save touchNo locally so we can tell when it changes globally
	local myTouchNo = touchNo
	for i = 1, 0, -.1 do
		-- Stop early if another blink started
		if touchNo ~= myTouchNo then break end
		-- Update the blink animation
		part.Reflectance = i
		pointLight.Brightness = i * 2
		wait(0.05)
	end
end
 
part.Touched:Connect(blink)

What this script does is it makes a part flash a light whenever it is touched.

My question is: How do I make it fire only once?

I’ve read other posts saying to use something like disconnect(). I am a new scripter and still don’t understand how to use it properly.

1 Like

you can add a debounce variable and set it to false so that when you touch the light it wont fire it because it isnt true

First create a variable RBXScriptConnection : local connect
get by connect= part.Touched:Connect(blink)
Then in function disable it connect:disconnect()
Ok, it’s here:

local part = script.Parent
 
-- Add a light
local pointLight = Instance.new("PointLight", part)
pointLight.Brightness = 0
pointLight.Range = 12
local connect
local touchNo = 0
local function blink()
	connect:disconnect()
	-- Advance touchNo to tell other blink() calls to stop early
	touchNo = touchNo + 1
	-- Save touchNo locally so we can tell when it changes globally
	local myTouchNo = touchNo
	for i = 1, 0, -.1 do
		-- Stop early if another blink started
		if touchNo ~= myTouchNo then break end
		-- Update the blink animation
		part.Reflectance = i
		pointLight.Brightness = i * 2
		wait(0.05)
	end
end
 
connect= part.Touched:Connect(blink)

or easy than: disable Script : script.Disabled= true

1 Like

If you wish for this to only run once, you can set a debounce variable, think of a debounce as “delay” or a time interval between each time the event or whatever it is happens, you can learn more about debounce from this video by @Alvin_Blox

Alternatively, you can simply destroy the script once you are finished with it (if it has no more use of course) by doing script:Destroy()

2 Likes

Another way to accomplish this, is by using :Once()

local part = script.Parent

local pointLight = Instance.new("PointLight", part)
pointLight.Brightness = 0
pointLight.Range = 12

part.Touched:Once(function()
	for i = 1, 0, -.1 do
		part.Reflectance = i
		pointLight.Brightness = i * 2
		wait(0.05)
	end
end)