-
What do you want to achieve?
Successfully return a different value from a function every time I execute the function -
What is the issue? Include screenshots / videos if possible!
Basically I am making a function that finds the closest enemy from a tower ( like the ones in tower defense games where it finds the closest enemy ). It does work and finds the closest enemy when I run the function. However, after setting a variable as the closest enemy found from the first execution of the function, it doesn’t “renew” the variable and keeps on thinking the same enemy is the closest one ( which in this case shouldn’t be since I execute the function in a loop every 1 second and it should give me a new closest enemy each time ).
here is the code of the function findClosestEnemy()
function findClosestEnemy()
for i, v in ipairs(game.Workspace.Enemies:GetChildren()) do
if v then
local enemyHumanoidRoot = v:FindFirstChild("HumanoidRootPart")
if enemyHumanoidRoot then
if (enemyHumanoidRoot.Position - towerHumanoidRoot.Position).Magnitude < radius.Value then
local distance = (enemyHumanoidRoot.Position - towerHumanoidRoot.Position).Magnitude
if distance < nearestDistance then
nearestDistance = distance
closest = v
end
end
end
return closest
end
end
end
here is the code for the loop:
while true do
local closest = findClosestEnemy()
wait(1)
print(closest)
end
-
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I have tried to make it renew the closest enemy everytime by not making a variable closest in the loop everytime, but using an existing variable closest and set the function to the existing variable closest. It does not work. I have tried to print the value closest and see if it does change, it doesn’t.
( as you can see here “normal” is the type of enemy and there are two types, speedy and normal. Every 1 second a speedy should be closer to the tower. The weird part is that I printed the distance that it generated and it DOES show the speedy enemy’s distance is shorter than normal’s distance, but it ignores that and keeps on putting “normal” as the closest enemy )
I searched youtube on tutorials and problems similar to mine but came up with nothing.
( also if I got some formatting wrong or meaning wrong I didn’t mean that. This is my first post in devforum and I would appreciate if somebody can help me with this )