Optimize Script

How woud I go by optimizing and improving this script? (If there are any)

local SearchDistance=15000
local hroot=script.Parent:WaitForChild("HumanoidRootPart")
local human=script.Parent:WaitForChild("Nextbot")
-- no touchy
local path
local waypoint
local oldpoints
local isWandering = 0

hroot.Walk:Play()

local function getNearestTorso()
	-- get nearest the nearest player, nearest distance, nearest character to our humanoid root part
	local nearesttorso = nil
	local nearestdistance = SearchDistance
	local neareastchar = nil
	local characters = game.Workspace:GetChildren()
	for _, v in pairs(characters) do
		if v:IsA'Model' and v ~= script.Parent and v:FindFirstChild("Player_Val") then
			local charroot = v:FindFirstChild'HumanoidRootPart'
			if charroot then
				local distance = (charroot.Position - hroot.Position).magnitude
				if distance < nearestdistance then
					nearestdistance = distance
					neareastchar = v
					nearesttorso = charroot
					
					--print(nearesttorso)
				end
			end
		end
	end
	
	return nearesttorso

end

workspace.CONFIG.SpeedModifier:GetPropertyChangedSignal("Value"):Connect(function()
	human.WalkSpeed=human.WalkSpeed*workspace.CONFIG.SpeedModifier.Value
end)

while wait() do
	
	local enemytorso = getNearestTorso()	
	
	if enemytorso ~= nil and (enemytorso.Position - hroot.Position).magnitude <= SearchDistance then -- if player detected
		-- pathfind to the torso
		local path = game:GetService("PathfindingService"):ComputeRawPathAsync(hroot.Position, enemytorso.Position, SearchDistance)
		if path.Status ~= Enum.PathStatus.FailFinishNotEmpty then -- if path is computed
			local points = path:GetPointCoordinates()
			if #points < 500 and path.Status==Enum.PathStatus.Success then -- if path is short enough
				-- start pathfinding
				print("correct")
				isWandering = 1
				oldpoints = points
				waypoint = 1
				human.MoveToFinished:connect(function()
					if waypoint < #oldpoints then
						waypoint = waypoint + 1
						--local Success, Error = pcall(function()
						human.WalkToPoint = oldpoints[waypoint]
						--end)
					else
						isWandering = 0
					end
				end)
				waypoint = waypoint + 1
				if oldpoints[waypoint] and path.Status==Enum.PathStatus.Success then
					--local Success, Error = pcall(function()
					human.WalkToPoint = oldpoints[waypoint]
					--end)
				end
			end
		end
	end
	
end

For context, the script is for one of the enemies in my game CaseOh’s Basics.

caseOhThink

return the distance in the getNearestTorso function so you don’t have to calculate it two times

you can also use a spatial hash or quadtree to check only the characters that are near each other

1 Like