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

Mouse.Target value keeps returning nil?

I'm trying to create a dialogue script where if I was to position my mouse onto an npc and pressed a certain key it would begin the dialogue. However, after putting some conditions the getMouseTarget function ends up returning nil even though my mouse is on an npc. I'd be happy if someone could show me where I messed up. Any help would be appreciated

local target 

function getMouseTarget()
	local mousetarget = mouse.Target
	if mousetarget and mousetarget:IsA("Model") and mousetarget:FindFirstChild("Humanoid") then -- Checks if the target is an actual humanoid compared to a normal model
		if game:GetService("Players"):FindFirstChild(mousetarget.Name,true) then -- If the humanoid isn't an actual player 
			target = mousetarget
		end
	end
end

mouse.Move:connect(getMouseTarget)
print(target.Name)

5 comments

0

Line 5, "if mousetarget" doesn't describe anything.

0

What do you mean it doesn't describe anything?

0

you can't say "If mouse.target then" because mouse.target isn't being watched to see if it targets a specific thing to activate the If function.

0

You have to specify an if function for every dialougue NPC that you have

0

if is not a function.

1 answer

✓ Accepted answer

###This is because the Target property is the BasePart that is under the mouse icon, nil if it's pointing to the sky. The expected result for you is to get the player. Since the target will be a body part, like the torso, Target.Parent will get the character, if it is a character.

local target 

local function getMouseTarget()
    local mousetarget = mouse.Target
    if mousetarget and mousetarget.Parent.ClassName == "Model" and mousetarget.Parent:FindFirstChild("Humanoid") then 
        if game:GetService("Players"):FindFirstChild(mousetarget.Parent.Name,true) 
            target = mousetarget
        end
    end
end

mouse.Move:Connect(getMouseTarget) -- :connect is deprecated, switch to :Connect
print(target.Name)

1 comment

0

Thanks that seemed to make it work. I appreciate it

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