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 run efficiently?

Asked by 8 years ago

As you can see, you may recognize this script from old zombie models that are instructed to follow you. However, I can't find any way to make this run faster, because if there are too many models using this script, the game runs too slow. I've tried making the loop slower and doesn't work.

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")

function findNearestTorso(pos)
    local list = game.Workspace:children()
    local torso = nil
    local dist = 100
    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")
            local player = game.Players:GetPlayerFromCharacter(temp2)
            if not player and (temp ~= nil) and (human ~= nil) and (human.Health > 0) and human.Parent.Name ~= "Zombie" then
                if (temp.Position - pos).magnitude < dist then
                    torso = temp
                    dist = (temp.Position - pos).magnitude
                end
                elseif player and (temp ~= nil) and (human ~= nil) and temp.Transparency ~= 1 and (human.Health > 0) and player.TeamColor ~= BrickColor.new("Bright green") 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(1)
    local target = findNearestTorso(script.Parent.Torso.Position)
    if target ~= nil then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    end
end

1 answer

Log in to vote
1
Answered by
Unlimitus 120
8 years ago

If this is in a Local Script, then use game:GetService("RunService").RenderStepped, which runs at 60 times a second. If you are using a Server Script (a regular script) then use game:GetService("RunService").Heartbeat. The server doesn't have access to RenderStepped.

Ad

Answer this question