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

How can I make this script find a player's "Humanoid" that isn't called "Humanoid"?

Asked by 4 years ago

In the game I'm creating the player's Humanoid name gets changed to "Player". When this happens the script will no longer work correctly. I tried many different things but nothing seemed to work. I'm an amateur scripter so I don't know all the ropes.

function findNearestTorso(pos)
    local list = game.Workspace:children()
    local torso = nil
    local dist = math.huge
    local temp = nil
    local human = nil
    local temp2 = nil
    for x = 1, #list do
        temp2 = list[x]
        if (temp2.className == "Model") and (temp2 ~= script.Parent) then
            temp = temp2:findFirstChild("Torso")
            human = temp2:findFirstChild("Humanoid") -- I tried changing Humanoid to "Player" but it didn't work either.
            if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
                if (temp.Position - pos).magnitude < dist then
                    torso = temp
                    dist = (temp.Position - pos).magnitude
                end
            end
        end
    end
    return torso
end




while true do
    wait(0.1)
    local target = findNearestTorso(script.Parent.Torso.Position)
    if target ~= nil then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    end

end

3 answers

Log in to vote
1
Answered by 4 years ago

What you're looking for is a method called FindFirstChildOfClass().

FindFirstChildOfClass() searches for an Instance by the given ClassName regardless of its name. Like FindFirstChild(), FindFirstChildOfClass() has a boolean recursive you can use for descendants.

For example, let's say we have a dummy rig containing a Humanoid named Soul. You can't do FindFirstChild("Humanoid") because FindFirstChild() searches by Name, not ClassName. You would use FindFirstChildOfClass("Humanoid"), which searches for any Humanoid regardless of its Name.

Example code:

local dummy = workspace:FindFirstChild("Dummy")
if dummy then
    if dummy:FindFirstChildOfClass("Humanoid") then
        print(dummy:FindFirstChildOfClass("Humanoid").Name) -- Prints Soul
    end
end
Ad
Log in to vote
0
Answered by
1ov3y0u 51
4 years ago

If the Humanoid is not named Humanoid, change "Humanoid"s name in the script to the Humanoid's name.

0
On the line that says "human = temp2:findFirstChild("Humanoid")" I tried that but it didn't work Michael_TheCreator 166 — 4y
0
If it didn't work, I don't know what to tell ya. You might have to remake the script. 1ov3y0u 51 — 4y
Log in to vote
0
Answered by
Elixcore 1337 Moderation Voter
4 years ago
Edited 4 years ago

Very simple in fact, instead of using :FindFirstChild("Humanoid")

All you have to do is use

 :FindFirstChildOfClass("Humanoid")

or

FindFirstChildWhichIsA("Humanoid")

both of them work.

Answer this question