How can I check if the player is pressing the left mouse button when the mouse is in front of the model?

I want the script to detect when the player is pressing and the mouse is in front of the model.

I tried to write this script every time but it failed and I got an error in output.I’ve tried the rest of everything from tutorials to DevForum posts.

This is my current script (not what i tried):

Current script (Without what I was trying to do)
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Camera = workspace.CurrentCamera
--locals

local mouse = game.Players.LocalPlayer:GetMouse() -- Gets the local player's mouse
local Decal = script.MouseDecal -- Finds the decal

game.Workspace.Pipe.ProximityPrompt.Triggered:Connect(function()
	--When ProximityPromt Triggered
	mouse.Icon = Decal.Texture
	--Change mouse icon
	game.Workspace.Pipe.ProximityPrompt.Enabled = false
	--Turn off the ProximityPromt
	
	repeat wait ()
		Camera.CameraType = Enum.CameraType.Scriptable
	until Camera.CameraType -- Enum.CameraType.Scriptable
	Camera.CFrame = workspace.Pipe.Camera.CFrame
	-- Custom camera
	
	--here I tried to put the script
end)

Sorry to everyone i didn’t have a script like this, but i doubted it.

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Button1Down:Connect(function()
	if Mouse.Target ~= nil then
		if Mouse.Target.Parent:IsA("Model") and Mouse.Target.Parent.Name ~= "Workspace" then
			print("model detected")
		end
	end
end)

Regarding this part I instead suggest to do:

Mouse.Target.Parent ~= workspace

instead of checking if it’s name is “Workspace”, as you can create folders and models named Workspace.

1 Like
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Button1Down:Connect(function()
	if Mouse.Target then
		if Mouse.Target.Parent:IsA("Model") then
			print("Model clicked!")
		end
	end
end)

The “Workspace” check doesn’t even need to be included. If the check for the mouse target’s parent being a “Model” instance passes then the mouse target’s parent can’t be the “Workspace” instance.

It is not true. When the part doesn´t have a parent model but the workspace it takes it as a model.

Mouse.Target.Parent:Destroy()

if you add this line in script and part.Parent is workspace then it print this:
The Parent property of Workspace is locked

image

local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Button1Down:Connect(function()
	if Mouse.Target then
		if Mouse.Target.Parent.ClassName == "Model" then
			print("Model clicked!")
		end
	end
end)

Indexing the ClassName property seems to be the way to go. Less overhead than calling an instance method too.

1 Like