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

The script lags a lot and I don't know why, help?

I am trying to make an NPC follow the nearest player it can find, however it lags a lot and i dont want this to happen, please help, my code:

Distance = 250

	while wait() do
	for i,Model in pairs(game.Workspace:GetChildren()) do
		if Model.ClassName == "Model" and Model ~= script.Parent then
			Humanoid = Model:FindFirstChild("Humanoid")
			if Humanoid ~= nil then
				if Humanoid.Health > 0 and Humanoid.Parent.Name ~= script.Parent.Name then
					Torso = Humanoid.Parent:FindFirstChild("Torso")
					if Torso ~= nil then
						if (Torso.Position - script.Parent.Torso.Position).Magnitude < Distance then
						script.Parent.Humanoid:MoveTo(Torso.Position)
						end
					end
				end
			end
		end
	end
end

2 comments

0

When is this script meant to be triggered?

0

This script is meant to go inside an NPC to make it follow a player, it triggers instantly and works but lags and I can't figure out why

1 answer

✓ Accepted answer

try this:

local Players = game.Players
local current_torso;
local NPC_torso = script.Parent.HumanoidRootPart

while wait() do
    for _, player in pairs(Players:GetPlayers()) do
	    local char = player.Character
            local root_part = char.HumanoidRootPart
            if not current_torso and char then 
                current_torso = root_part 
            elseif(char ~= current_torso.Parent and char) then
                local magnitude = (root_part.Position - NPC_torso.Position).Magnitude
                local old_magnitude = (current_torso.Position - NPC_torso.Position).Magnitude

                if(magnitude < old_magnitude) then
                    current_torso = root_part
                end

            end
            NPC_torso .Parent.Humanoid:MoveTo(current_torso.Position)
    wait();
    end
end

i am at school so forgivee me for errors

8 comments

0

Yea I am at school too.

0

If your answer works, I will accept it, can't test right now, maybe not till tomorrow, see if you can run it without lag, I will test it when I get back to my pc

0

It doesnt work, it lags like my script

0

umm in this case then the lag is in another script, b/c it worked with no problem when i tested it

0

i tested this in an empty baseplate template

0

try setting the speed of the npc your using to something like 70, then you will see my problem

0

well it worked for me, not sure why not for you, try again i changed the code a bit for optimization

0

well i edited your code a bit and mine as well, a simple piece of line that i dont know how removes the lag, so i accepted your answer but keep in mind that this not actually solve my problem

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