# This is making heaps of lag

This is making my games really slow, or it’s some other script.
But when I added this script it made the game go so very slow, any help?

``````#pragma strict

var lights : Light[];
var distance : float = 25;

lights = GameObject.FindObjectsOfType(Light);

function Update () {

for(var n : int; n < lights.Length; n++) {

if(lights[n].type == LightType.Directional)
n++;

if(n >= lights.Length)
return;

if(Vector3.Distance(transform.position,lights[n].transform.position) > distance)
lights[n].enabled = false;

else
lights[n].enabled = true;

}

}
``````

EDIT:

I’ve remade it, but the FPS has only gone up about 5-10.

``````#pragma strict

var lights : Light[];
var distance : float = 25;
var interval : float = 0.25;

lights = GameObject.FindObjectsOfType(Light);
DoUpdate();

function ReUpdate () {

DoUpdate();

}

function DoUpdate () {

for(var n : int; n < lights.Length; n++) {

if(lights[n].type == LightType.Directional)
n++;

if(n >= lights.Length)
return;

if(Vector3.Distance(transform.position,lights[n].transform.position) > distance)
lights[n].enabled = false;

else
lights[n].enabled = true;

yield WaitForEndOfFrame;

}

yield WaitForSeconds(interval);
ReUpdate();

}
``````

Vector3.Distance involves taking at least one square root. That is quite an expensive operation. To make matters worse, you’re doing it multiple times every frame.

You will most likely notice an improvement if you use sqrMagnitude instead:

`````` if((transform.position-lights[n].transform.position).sqrMagnitude > distance*distance)
``````