So basically I have an enemy for my RPG. I have been trying to cut down this code without it taking up too higher percentage on the script performance output. This is because usually i have an RPG with about 140 Enemies, and of course too many scripts causes roblox to lag.
function findNearestTorso(pos) -- Find the character
local list = game.Workspace:GetChildren()
local Torso
local temp
local Distance = 10
local humanoid
local temp2
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("Torso")
humanoid = temp2:findFirstChild("Humanoid")
if temp and humanoid and humanoid.Health > 0 then
if (temp.Position - pos).magnitude < Distance then
Torso = temp
Distance = (temp.Position - pos).magnitude
else
Humanoid:MoveTo(NPCSpawn.Position, NPCSpawn)
end
end
end
end
return Torso
end
while Figure.Parent do -- figure being the humanoid in this guy
wait(n)
local Target = findNearestTorso(Torso.Position) -- player
if Target then
Humanoid:MoveTo(Target.Position, Target)
TouchValue.Value = true
n = 0.1
local amt = RunService.Stepped:wait()
if amt > nextTime then -- make this guy walk correctly!
move(amt)
nextTime = amt + .01
else
NPCSpawn.Touched:connect(function() -- The NPCSpawn is where the enemy spawns, when a player moves out of radius, the enemy will go back to spawn
wait(0.2)
script.Touching.Value = false
n = 0.7
end)
end
end
end
And of course this runs frequently to check whether there is a player. This animation script is very.. all over the place. i was wondering if there was an easier way of detecting a player, for example adding a big (transparent) block in the enemy, and when it is touched it shall chase the player. But Ive got some welding probs with that. Anyway, thanks for the help if you actually read all of this ha ~ thx bubs

1 comment
thanks, ill try to add one script to all NPCs with one script