How do I Unbind a key input if an attribute is true

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
  • Sorry if the title is unclear. I want to write a code that uses ContextActionService to unbind a key depending on an attribute of the player.
  1. What is the issue? Include screenshots / videos if possible!
  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
  • I tried using stringValue instances, but the same problem occurred and it came along with the “attempt to index nil” error and I’d rather use attributes anyway.
    I basically don’t want the player to press 1 if “C1” is already set to true. What should I do so that this script checks the attribute?

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local plr = game:GetService("Players").LocalPlayer

local folderC1 = ReplicatedStorage.Characters:WaitForChild("C1")  -- Assuming "C1" is the folder

local function onAction(actionName, inputState, inputObject)
	if inputState == Enum.UserInputState.Begin then
		-- Perform action when "1" key is pressed down
		print("Cannot Swap")
	end
end

local function updateActionBinding()
	if #folderC1:GetChildren() == 0 or plr:GetAttribute("C1") then
		-- Bind if folder is not empty
		ContextActionService:BindAction("Unbind", onAction, false, Enum.KeyCode.One)
	else
		-- Unbind if folder is empty
		ContextActionService:UnbindAction("Unbind")
	end
end

-- Initial update
updateActionBinding()

-- Listen for changes in folder content
folderC1.ChildAdded:Connect(updateActionBinding)
folderC1.ChildRemoved:Connect(updateActionBinding)

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

Instead of checking children, you could try using :GetAttributeChangedSignal(). This will fire whenever the attribute changes and would be better for your situation. You could then control a Boolean based on this and unbind/bind the action based on the Boolean.

Could you elaborate on what you mean by “control a boolean”? Do you mean once the attribute changes i can make it detect what exactly it changed to?

I mean if you make a Boolean at the top of your script:

local attribute = false

you can control this Boolean through the attribute:

Player:GetAttributeChangedSignal("C1"):Connect(function()
    attribute = Player:GetAttribute("C1")
end)

and you could check it throughout your script. It saves calling GetAttribute every time.

I got it to work, thank you I appreciate it,

1 Like

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