- Home /
Question by
CanCo · Sep 15, 2013 at 01:07 AM ·
javascriptlagslow
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();
}
Comment
Best Answer
Answer by Jamora · Sep 15, 2013 at 01:25 AM
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)
Your answer
Follow this Question
Related Questions
Adding gravity to my gameobject causes lagg 1 Answer
javascript drops over 30 fps 0 Answers
Bad Performance on Mobile. 0 Answers
How can i make my scene less laggy? 2 Answers
Big Delay in Networking 0 Answers