Need help with ContextActionService

Here is my code:


local Part = game.Workspace.Part
local function onButtonYellow()
	Part.BrickColor = BrickColor.new("New Yeller")
end

local function onButtonRed()
	Part.BrickColor = BrickColor.new("Really red")
end

ContextActionService:BindAction("turnBrickYellow", onButtonYellow, true, "d")
ContextActionService:BindAction("turnBrickRed", onButtonRed, true, "d")
wait(5)
ContextActionService:UnbindAction("turnBrickRed")

I want to make it so whenever a player pressed the d key the part turn red and when the player clicked the d key again the part colour will change back to yellow

any help is appreciated :slightly_smiling_face:

You have to use Enum.KeyCode, not strings. Also, you can use an unofficial ternary operation to change the color.

local Part = game.Workspace.Part
local function onButtonYellow()
	Part.BrickColor = part.BrickColor == BrickColor.new("Really red") and BrickColor.new("New Yeller") or BrickColor.new("Really red")
end

ContextActionService:BindAction("turnBrickYellow", onButtonYellow, true, Enum.KeyCode.D)
wait(5)
ContextActionService:UnbindAction("turnBrickYellow")

If you don’t know what the ternary operator is you could also do this:

Couldn’t you just check for a String (Or the current Color) Value to change them separately? You don’t need to use 2 functions to connect them, cause I believe they’ll just fire at the same time

local Part = game.Workspace.Part
local CurrentColor = "Red"

local function ChangeColor()
    if CurrentColor == "Red" then
	    Part.BrickColor = BrickColor.new("New Yeller")
        CurrentColor = "Yellow"

    elseif CurrentColor == "Yellow" then
    	Part.BrickColor = BrickColor.new("Really red")
        CurrentColor = "Red"
    end

end

ContextActionService:BindAction("Change", ChangeColor, true, Enum.KeyCode.D)
wait(5)
ContextActionService:UnbindAction("Change")

it does not work with Enum.Keycode

It could be due to how quick you’re unbinding the action? Try removing that line briefly for a moment, or you need to change it to a LocalScript & put it inside StarterPlayerScripts

I already put in the local scripts

ContextActionService:UnbindAction("Change")

Remove or comment this then, another thing you can check for is by adding print() statements to see what works & what doesn’t

I removed it what is the next step?

Play test it again

If it didn’t work, again consider adding print() statements so you can debug where the issue may lie