Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Problem with KeyDown event on my code?

So, basically I have this code that is trying to give a player a ball when "b" is pressed on their keyboard. This works in studio, but when tried in-game I get an error saying "attempt to index global 'mouse' a nil value". Any ideas?

game.Players.PlayerAdded:connect(function(player)
	local mouse = player:GetMouse()
	mouse.KeyDown:connect(function(key)
		if key == "b" then
			game.ReplicatedStorage.Ball:Clone().Parent = player.Backpack
		end
	end)
end)

1 comment

1

KeyDown is deprecated, you should use UserInputService or ContextActionService instead.

1 answer

:GetMouse() can only be accessed by a LocalScript, attempting to use a script will error.

local Mouse = Game.Players.LocalPlayer:GetMouse()

Mouse.KeyDown:connect(function(k)
	if key == "b" then
		game.ReplicatedStorage.Ball:Clone().Parent = player.Backpack
	end
end)

1 comment

0

Check the capitalization of Mouse.

This discussion is preserved as it was. New answers, comments, and votes are closed.