Keycode working while false?

I would like a key code to only work while something is true. If the value is false, they shouldn’t be able to do the key code.

The script accurately detects when the value is changed, and what it was changed too, but they key code works while false instead of only while true.

In the screenshot, changed is printed every time the value changes. Ready = true, NotReady = false. The script detects that just fine.

I couldn’t find any potential solutions, however I am pretty new to scripting.

The script is simple, but I don’t get why it doesn’t work.

wait(0.05)
local BV = script.Parent.BayonetV



BV:GetPropertyChangedSignal("Value"):Connect(function()
	print("changed")
	if BV.Value == true then
		print("Ready")
		local UserInputService = game:GetService("UserInputService")
		local Key = Enum.KeyCode.G
		UserInputService.InputBegan:Connect(function(InputObject, GameProcessedEvent)
			if InputObject.KeyCode == Key then
				print("stabby")			
			end
		end)
		
	elseif BV.Value == false then
		print("NotReady")
	end
end)```

Remember to disconnect your connections

Events | Roblox Creator Documentation.

1 Like

Where and how should I add a disconnect? I tried it like this, but it comes back with an error saying “Disconnect is not a valid member of InputObject “InputObject””. I also tried it on UserInputService and that didn’t work either

local BV = script.Parent.BayonetV
local UserInputService = game:GetService("UserInputService")
local Key = Enum.KeyCode.G


BV:GetPropertyChangedSignal("Value"):Connect(function()
	print("changed")
	if BV.Value == true then
		print("Ready")
		UserInputService.InputBegan:Connect(function(InputObject, GameProcessedEvent)
			if InputObject.KeyCode == Key then
				print("stabby")		
				InputObject:Disconnect()
			end
		end)
		
	elseif BV.Value == false then

		print("NotReady")
	end
end)```

Consider structuring your code so that you only have the InputObject event instead of the BV event aswell

UserInputService.InputBegan:Connect(function(k, gp)
  if BV.Value then

  else

  end
end)

The code you posted has a serious memory leak problem.

local UserInputService = game:GetService("UserInputService")
local BV = script.Parent:WaitForChild("BayonetV")

BV:GetPropertyChangedSignal("Value"):Connect(function()
	print("changed")
	if BV.Value then
		UserInputService.InputBegan:Connect(function(InputObject, GameProcessedEvent)
			if InputObject.KeyCode == Enum.KeyCode.G then
				print("stabby")			
			end
		end)
	else
		print("NotReady")
	end
	UserInputService.InputBegan:Disconnect()
end)