This seems quite simple, but it is not working. Can someone review my code and tell me what I did wrong?
local Player = game.Players.LocalPlayer
local Character = Player.Character
local Mouse = Player:GetMouse()
local Enabled = true
Mouse.KeyDown:connect(function(key)
if Enabled == false then
return
end
key = key:lower()
if key == "q" then
Enabled = false
local b1 = Instance.new("Part")
b1.Shape = "Ball"
b1.Material = "Neon"
b1.BrickColor = BrickColor.new("Hot Pink")
b1.Parent = Character
b1.CFrame = Character.Torso.CFrame*CFrame.new(0,0,-5)
end
Enabled = true
end)
It appears you are using key:lower() incorrectly by trying to change the key variable. Be mindful that the key variable is already set once the function is fired, and the variable is the key you pressed.
Replace the key = key:lower() and the if key == q statement with this; hope this helps!
if key:lower() == "q" then
Enabled = false
local b1 = Instance.new("Part")
b1.Shape = "Ball"
b1.Material = "Neon"
b1.BrickColor = BrickColor.new("Hot Pink")
b1.Parent = Character
b1.CFrame = Character.Torso.CFrame*CFrame.new(0,0,-5)
end
The issue is you’re trying to access Character before it exists.
This code will detect when the character gets added and update the Character variable, and the KeyDown event will return if Character is nil.
local Player = game.Players.LocalPlayer
local Character = Player.Character
local Mouse = Player:GetMouse()
local Enabled = true
Mouse.KeyDown:connect(function(key)
if Enabled == false then
return
end
if (Character == nil) then
return;
end
key = key:lower()
if key == "q" then
Enabled = false
local b1 = Instance.new("Part")
b1.Shape = "Ball"
b1.Material = "Neon"
b1.BrickColor = BrickColor.new("Hot Pink")
b1.Parent = Character
b1.CFrame = Character.Torso.CFrame*CFrame.new(0,0,-5)
end
Enabled = true
end)
Player.CharacterAdded:Connect(function()
Character = Player.Character
end)
Or, as @Cadentopia said, you could just move local character = Player.Character into the KeyDown event which is much more simple.
You can also retrieve the character as the function is called. Move the local Character line into the function as the first line, just for a less complex entrance.
Mouse.KeyDown has been long deprecated in favor of UserInputService. And as even mentioned on the API page for KeyDown. You should be using UserInputService for all new work.
It’s not at all very complex to learn. So you should very well be able to adapt your code easily to use UIS.
Example:
local UIS = game:GetService("UserInputService")
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
UIS.InputBegan:Connect(function(input, GP)
if input.KeyCode == Enum.KeyCode.E and not GP then
--Code
end
end)