Lots of Lag When Using Raycasting

Okay so there’s a lot of code in this game and I can’t put it all so I will go over the gist of it:

(NPC code) - note* there are usually 30-40 NPCs in the game at any given time:

  1. NPC looks through players and a folder with other NPCs and finds a target
  2. NPC casts a ray and detects objects obstructing their shot to their target until there is nothing obscuring it (every .5 seconds)
  3. Once there is a clear path to the target, they shoot a bullet to the player; that is where the NPC code ends

(Bullet code):

  1. Bullet flies in one direction until it hits something
  2. Bullet creates ray and does a loop of FindPartOnRayWithIgnoreList until there are no more parts, thus finding all parts from the original position of the NPC’s gun onward in a 5000 stud long vector
  3. Runs a for loop and stops when the part on the ray is the same part it hit
  4. Spawns a singe mark and a part with some particle effects at the point of impact and creates a sound
  5. Bullet is destroyed and the particles part and the singe mark are deleted shortly after

the NPC will repeat this cycle indefinitely until either its target is killed or its view to its target is obstructed for more than 5 seconds.

I have included a video of this. I only added the raycasting effects to the bullet today and it works perfectly fine without it. You can also witness the lag for yourself here: [Beta] Star Wars: Battalion 212th - Roblox

Note* I have heard people say that I should handle raycasting on the client but most of the time it’s NPCs firing at other NPCs so I don’t know which client to run it on.

Video: Roblox 2020-06-07 17-24-17.mp4 - Google Drive