Hello!
I was making a script, and I ran into a problem.
I need the npc to detect if theres any humanoids, player or not.
But it only detected itself, so I did “and not (v == script.Parent)” but that made it not detect anything.;
Here is my script
local children = workspace:GetChildren()
for i, v in pairs(children) do
if v:FindFirstChild("Humanoid") and (v.ClassName == "Model") and not (v == parent) then
local char = v
local hrp = char.HumanoidRootPart
local humanoid = v.Humanoid
print(char.Name)
end
end
Hey! You cannot get humanoid from workspace. You can however get the player character from workspace. I however would do it like this:
local Children = game.Players:GetChildren()
for i = 1, #Children do
--Children.Character is how u get character
--Children.Character.Humanoid is how u get humanoid of the player
print(Children.Character.Humanoid.DisplayName)
end
So, it’s FindFirstChildOfClass because you can get to see Humanoid to the script you want.
Also, consider changing it at a LocalScript if it’s not working.
Oh, I forgot two things that’s unlisted:
I will put a wait() (Meaning to the wait(), meaning to the task.wait().).
Every local has a a Capital Letter after local.
local Children = workspace:GetChildren()
task.wait(0.02 or 1/50)
for i, v in pairs(children) do
if v:FindFirstChild("Humanoid") and (v.ClassName == "Model") and not (v == parent) then
local Character = v or game.Players.LocalPlayer.Character
local HRP = char.HumanoidRootPart
local Humanoid = v.Humanoid or Character:FindFirstChildOfClass("Humanoid")
print(Character.Name)
end
end
local Children = game.Players:GetChildren()
for i = 1, #Children do
--Children[i].Character is how u get character
--Children[i].Character.Humanoid is how u get humanoid of the player
print(Children[i].Character.Humanoid.DisplayName)
end
wait(10)
local Children = game.Players:GetChildren()
for i = 1, #Children do
--Children[i].Character is how u get character
--Children[i].Character.Humanoid is how u get humanoid of the player
print(Children[i].Character.Humanoid.DisplayName)
end
The problem is that the character does not load at the correct time (i.e., you are checking before any player has been loaded). If you yield the code, it will work successfully.
-- will wait for the first player to join, and their character to be loaded
game:GetService("Players").PlayerAdded:Wait().CharacterAdded:Wait()
local children = workspace:GetChildren()
for i, v in pairs(children) do
if v:FindFirstChild("Humanoid") and (v.ClassName == "Model") and not (v == parent) then
local char = v
local hrp = char.HumanoidRootPart
local humanoid = v.Humanoid
print(char.Name)
end
end
Alternatively, you could repeat until a player is found.