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

Mouse Find Multiple targets?

Question Is it possible to make a mouse script to allow a player to detect multiple targets via one script?
Problem My code keeps getting the fallowing error: Players.Player.PlayerScripts.LocalScript:5: attempt to index global 'Target' (a nil value)
Code

mouse = game.Players.LocalPlayer:GetMouse()
terminals = game.Workspace.Model:GetChildren()
while wait() do
Target = mouse.Target
if Target:FindFirstChild(terminals) then
if Target.terminals.Value == true then
print("Found")
elseif not Target:FindFirstChild(terminals) then 
print("End")
end
end
end

Thanks

1 answer

✓ Accepted answer

Mouse.Target can be nil
Fix this by using a conditional statement to determine if the Target is nil (if the Player is looking at the skybox, for example)

mouse = game.Players.LocalPlayer:GetMouse()
terminals = game.Workspace.Model:GetChildren()
while wait() do
Target = mouse.Target
if Target and Target:FindFirstChild(terminals) then
if Target.terminals.Value == true then
print("Found")
elseif not Target:FindFirstChild(terminals) then 
print("End")
end
end
end

You may also want to consider using Mouse.Moved alongside a loop with a longer wait
Why? The Player is only going to be looking to use mouse input if they're actually moving their mouse, and driving your input with events is a much better practice than lazy polling. If they're simply moving their mouse over something by moving their Character for example, they're not going to need such an immediate response and you can cut down on idle loops when they're not needed.

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