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
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
If the Humanoid is not named Humanoid, change "Humanoid"s name in the script to the Humanoid's name.
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.