How to make this script work with mobile and PC

I have a local script that makes a CAS button appear, however it does not work on computer at the moment because of 1 issue I will explain.

first, this is what makes the button.

				local AbilityButton = ContextActionService:GetButton("Ability")
				AbilityButton.SizeConstraint = Enum.SizeConstraint.RelativeXX
				AbilityButton.Image = "rbxassetid://5743593320"
				AbilityButton.PressedImage = "rbxassetid://5743593320"
				AbilityButton.ImageColor3 = Color3.new(0, 1, 0)
				AbilityButton.Size = UDim2.new(0.3, 0, 0.3, 0)
				AbilityButton.Position = UDim2.new(0.15, 0, 0.25, 0)
				AbilityButton.ImageTransparency = 0.5

that works well, this is the script that has the problem:

local AbilityButton = ContextActionService:GetButton("Ability")
AbilityButton.Image = "rbxassetid://5743593320"
AbilityButton.ImageColor3 = Color3.new(0, 1, 0)
Cooldown("Ability", 5)

notice the problem? at the top of the script I reference “AbilityButton”. however, this button does not exist on computer as its a keybind on computer, not a GUI button. so defining this causes a yield on computer, but it works fine on mobile.

I tried fixing this by wrapping it in if UserInputService.TouchEnabled then like shown below.

if userInputService.TouchEnabled then
	local AbilityButton = ContextActionService:GetButton("Ability")
end

Cooldown("Ability", 5)

if UserInputService.TouchEnabled then
	AbilityButton.Image = "rbxassetid://5743593320"
	AbilityButton.ImageColor3 = Color3.new(0, 0.607843, 0)
end

but that returns the following errors when on mobile, wrapping it in TouchEnabled works fine for PC though.

errors:

ContextActionService: Unexpected error while invoking callback: Workspace.me7474.CharacterControl:60: attempt to index nil with 'Image
Workspace.me7474.CharacterControl:86: attempt to index nil with 'Image'

anyone know what Im doing wrong? thanks in advance.

Why not just use:

AbilityButton.TouchTap:Connect(function()
       -- Your code here
end)

Can’t you just rename it🤨. Although you could detect if a user has a keyboard attached with UserInputService.KeyboardEnabled to make a GUI button instead, depending on the outcome.

lol I think I found the problem.

if userInputService.TouchEnabled then
	local AbilityButton = ContextActionService:GetButton("Ability")
end

Cooldown("Ability", 5)

if UserInputService.TouchEnabled then
	AbilityButton.Image = "rbxassetid://5743593320"
	AbilityButton.ImageColor3 = Color3.new(0, 0.607843, 0)
end

Im using 2 different if statements here, in the first one I defined the variable used in the second with local.