How to toggle flashlight using contextActionService

i made a flashlight script for mobile devices, but if i stop holding the button, the flashlight turns off, how do i make it, so when i click, the flashlight toggles, and dont turn off after stop i holding it

local contextActionService = game:GetService("ContextActionService")

function onButtonPress()
		local player = game.Players.LocalPlayer
		local playerChar = player.Character
		local playerLight = playerChar.Head:FindFirstChild("Light")

		if playerLight then
			playerLight:Destroy()
		else
			local  light = Instance.new("SurfaceLight",playerChar:FindFirstChild("Head"))
			light.Name = "Light" -- Edit your light
			light.Range = 30
			light.Angle = 80
			light.Shadows = true
			light.Brightness = 3
		end
	end
local mobilebutton = contextActionService:BindAction("Flashlight", onButtonPress, true,"Flashtoggle")
contextActionService:SetPosition("Flashlight",UDim2.new(0.32,-25,0.55,-25))
contextActionService:SetImage("Flashlight","rbxassetid://10565842565")

You have to change your function to check for the action type. Your function runs anytime there is any action so anytime an action Begins, Ends, Changes, or Cancels. And you have no way right now to determine between them.

Lucky for you when binding an action, if you pass in a function (like you are doing) it gives your function the: action’s name, input state, and input object!

Update your function to use these parameters:

local FlashlightToggle = false

function onButtonPress(actionName, inputState, inputObject)
	if actionName == "Flashlight" then
		if inputState == Enum.UserInputState.Begin then
			local player = game.Players.LocalPlayer
			local playerChar = player.Character
			local playerLight = playerChar.Head:FindFirstChild("Light")

			if FlashlightToggle and playerLight then
				playerLight:Destroy()
				FlashlightToggle = false
			else
				FlashlightToggle = true
				local  light = Instance.new("SurfaceLight",playerChar:FindFirstChild("Head"))
				light.Name = "Light" -- Edit your light
				light.Range = 30
				light.Angle = 80
				light.Shadows = true
				light.Brightness = 3
			end
		end
	end
end
1 Like