Turrets using while loops causes drastic loss of FPS

So in a tower defense game that I have been working on I have turrets along a path, and they each use while loops to detect and damage targets. Are there any other options I could use instead of while loops to not have such a performance impact?

What is the task.wait time in the loop of your scripts?
If you increase the time by a bunch (say from () to (5)) does the lag decrease?
If it does then the wait is the issue. If the lag doesn’t change then you’ve got something else going on.
Post your script so we can see it.

I use Matter by @evaera, which is an ECS library and very performant, I suggest u check it out.

task.wait and while true are bad practices, and there r much more efficient ways to achieve it.

Yes, but I wanted to know how they were handling the situation and offered some troubleshooting info to get some idea of what was going on.
That’s why I asked for their script.

I suggest using RunService, i use it for my own projects.

How can I find it, I went though their profile and found nothing

Matter

My advice:

Components

Make sure all ur turrets have a component called Turret or smth like tht with the value of the turret’s position. Insert another component called Target also which will hold the Instance it shud be shooting.

Along with that, all ur NPCs, aka enemies, must also have a common component, smth like Enemy with reference to the enemy’s position will be fine. For movement of the enemies, I suggest having another component called WalkTo, which will hold a CFrame/Vector3 for movement.

Systems

Main:

Turret TragetLocking

Under this system, run a world:query(Components.Enemy, Components.WalkTo) loop inside another world:query(Components.Turret) loop. Then check the magnitude between the npc and turret and if it is less than the previous npc distance, which can b got from checking the magnitude in Target component and Turret position.l, initially u mite want to check if Target is nil and assign it to the first npc. (You can also store the distance in another component Distance for more efficiency).

Turret Shooting

Uder this system, run a world:query(Components.Turret, Componets.Target), and perform the shooting logic based on the Target.

So that’s it, if u have any ques, feel free to ask 'em here. Ik its kinda advanced, but its uses are unlimited.

I settled on using parts with Touched events, this is the best option I could find for performance.