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

Why dosen't keydown work with mouse.Target?

So, so if you read the title i cant understand why KeyDown isnt working with Mouse.Target so. I want it to be so if you have the mouse on the item on the Part and then press F then that part/model will remove from the workspace but i wont get the KeyDown to work with Mouse.Target why?

Script:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local camera = workspace.CurrentCamera
local Keys = {}

while true do
	wait(0.1)
	if mouse.Target ~= nil then
		if mouse.Target.Parent.Name == "Items" then
		    if Keys[Enum.KeyCode.R] then
				print('hi')
		end
		else
		    script.Parent.Visible = false
			print('nil')
		end
	end
end

1 answer

✓ Accepted answer

Don't use KeyDown

KeyDown is deprecated. Not that you're using it in the first place, but it seems like you tried. Use UserInputService instead.

Don't use loops

There are events for a reason. To see all the events for something, look at the wiki for the service or Instance.

Setting up the event

First, we have to get the service. To do this, we can use the GetService function. After we get the service, we can use the event, InputBegan, on the service. After that, we can check if the InputObject is a KeyCode, and the correct key.

--Local Script
local UIS = game:GetService("UserInputService")

UIS.InputBegan:connect(function(InputObject)
	if InputObject.KeyCode = Enum.KeyCode.R then
		print("Pressed R!")
	end
end)

Deleting the part

It seems like you're using a model, but since I don't know if you are, I'll be making my example off of a part. Just get the mouse, then check the mouse Target.

--Local Script
local UIS = game:GetService("UserInputService")

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

UIS.InputBegan:connect(function(InputObject)
	if not mouse.Target then return end
	if InputObject.KeyCode = Enum.KeyCode.R then
		local targ = mouse.Target
		if targ:IsA("Part") then
			targ:Destroy()
		end
	end
end)

Good Luck

If I helped, please don't forget to accept my answer.

5 comments

0

Thanks, it worked but if i want a model instead of a part what do i do then?

0

if targ.Parent.Name == "name" then on line 11, or something.

0

If i do that then the thing inside the model just destroys and have to press R multiple times on all the parts?

0

Also destroy the model, not the part on line 12. targ.Parent:Destroy()

0

Thanks ;)

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