ID:310485
 
(See the best response by LordAndrew.)
So I'm trying to construct a tower to where when it is built it searchs for enemies in it's range, but everytime I implement it into my game it makes the game considerably slower and produces a lot of lag. I'm assuming there is something wrong with my code, so I'll post it below.

obj/Towers
icon = 'Towers.dmi'
Arrow
Range = 5
Speed = 10
Top
icon_state = "top"
layer = MOB_LAYER + 1
pixel_y = 32
Bottom
icon_state = "bottom"
New()
..()
spawn()
Search()
proc/Search()
while(src)
for(var/mob/Grundies/G in world)
if(G)
if(G in view(src.Range,src))
var/obj/Projectiles/Arrow/A = new /obj/Projectiles/Arrow(src)
walk_to(A,G)
else
break()
sleep(src.Speed)

Any suggestions?
Best response
I'm not quite sure why you're searching for every "Grundies" in the world, asserting it exists, then seeing if "Grundies" is in view. You could just as easily do for(var/mob/Grundies/G in view(Range, src). When working with for(), you don't need to do if(G) to see if it exists, for() already handles the check for that.

var/obj/Projectiles/Arrow/A = new /obj/Projectiles/Arrow(src) is also redundant. You've already told the compiler you wish to create a new instance of obj/Projectiles/Arrow stored as the instance A. var/obj/Projectiles/Arrow/A = new(src). Also did you mean to spawn the projectile inside of the turret? If not you'd want to place it at src.loc.

-----------------------------

Hrm. I gave your code a test and I can spot a huge problem with it. The projectiles never delete themselves and just follow the player around instead of doing any sort of collision magic. I can understand it getting laggy if you have a ton of towers shooting at the player and projectiles building up under them.

I just wrote this up pretty quickly, and it could stand to be more robust but it's a rudimentary idea of how to handle projectiles and towers:

obj
projectile
proc
move_to(mob/m)
if(!m) return

while(step_towards(src, m))
sleep(1)

// Alternatively you can do del src here.
loc = null

New(newloc, mob/m)
spawn move_to(m)

arrow
icon_state = "arrow"

density = TRUE

Bump(mob/m)
if(istype(m))
world << "Bumped [m]."

loc = null

tower
var
speed = 0
range = 0

arrow
icon_state = "bottom"

speed = 10
range = 5

proc
search()
while(src)
for(var/mob/m in view(range, src))
new /obj/projectile/arrow(loc, m)

sleep(speed)

New()
spawn search()

mob
icon_state = "me"

verb
new_tower()
new /obj/tower/arrow(loc)