I am working on a tower defense styled game and so I made a tower script that gets the zombies within range of the tower and then does a "for i" loop to get which one is the furthest, but when I run the script it keeps targetting the wrong zombies, I tried several things to fix it but to no avail and I need some support.
Script: (Serverside)
--//Services local players = game:GetService("Players") local repStorage = game:GetService("ReplicatedStorage") --//Variables local tower = script.Parent local towerHumanoidRootPart = tower:WaitForChild("HumanoidRootPart") local towerAnimations = tower:WaitForChild("TowerAnimations") local towerSoundEffects = tower:WaitForChild("TowerSoundEffects") local towerStats = tower:WaitForChild("TowerStats") local pathsFolder = workspace:WaitForChild("PathsFolder") local function shoot() while wait(.01) do for i, v in pairs(pathsFolder:GetChildren()) do local zombiesFolder = v:WaitForChild("Zombies") for i, z in pairs(zombiesFolder:GetChildren()) do local zombieHumanoidRootPart = z:WaitForChild("HumanoidRootPart") if (zombieHumanoidRootPart.CFrame.p - towerHumanoidRootPart.CFrame.p).magnitude <= require(towerStats).Range then local zombiesDistanceWalkedValues = {} local zombieStats = z:WaitForChild("ZombieStats") local zombieDistanceWalked = zombieStats:WaitForChild("DistanceWalked") table.insert(zombiesDistanceWalkedValues, zombieDistanceWalked.Value) local furthestDistance = 0 for i, d in pairs(zombiesDistanceWalkedValues) do if d > furthestDistance then furthestDistance = d end end if zombieDistanceWalked.Value == math.max(furthestDistance) then towerHumanoidRootPart.CFrame = CFrame.new(towerHumanoidRootPart.CFrame.p, zombieHumanoidRootPart.CFrame.p) towerHumanoidRootPart.Orientation = Vector3.new(0, towerHumanoidRootPart.Orientation.Y, 0) wait(require(towerStats).FireRate - .01) end end end end end end --//Callers shoot()
This is a problem concerning the scope of the zombieDistanceWalked
table. Since the table is inside the for loop, on each iteration, a separate table is formed which does not have data from previous iterations. The table is completely new. To overcome this, you should place the table in the scope that encloses the for loop itself — right above the for loop for example — where the table can be accessed with previous data within iterations.
On another note, a simpler way to do this is inserting values, using table.sort() and picking the suitable value. The sorting and then retrieving the suitable value would be done below the loop, after all values have been inserted.