Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Mouse.Target value keeps returning nil?

Asked by 5 years ago

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)
0
Line 5, "if mousetarget" doesn't describe anything. UnluckyTW 0 — 5y
0
What do you mean it doesn't describe anything? User#19524 175 — 5y
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. UnluckyTW 0 — 5y
0
You have to specify an if function for every dialougue NPC that you have UnluckyTW 0 — 5y
0
if is not a function. User#19524 175 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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)

0
Thanks that seemed to make it work. I appreciate it JinxedJord_n 15 — 5y
Ad

Answer this question