- Home /
Help for code optimization
Hi guys I need some help for optimize this come, usually this doesn't make problem on pc, but it makes the game framerate drop on android
function OnTriggerStay (other : Collider) {
if(other.gameObject.tag == "Player"){
var player : GameObject = other.gameObject;
if(!found){
var dir : Vector3 = player.transform.position - transform.position;
transform.Translate(dir.normalized * Time.deltaTime * 15 * (1/dir.magnitude*2));
}
if(dir.magnitude < 1){
if(!found)
player.SendMessage("AddEnergy",energy);
found = true;
gameObject.light.enabled = false;
if(isPowerup){
particleSystem.loop = false;
other.GetComponent(playercontroller).bullet_speed += bullet_factor;
other.GetComponent(playercontroller).speed += speed_factor;
other.GetComponent(playercontroller).reload_speed -= reload_factor;
}
else
{
gameObject.renderer.enabled = false;
}
yield new WaitForSeconds(2.5);
Destroy(gameObject);
}
}
}
I'm using this for making some energyballs that are attracted from the player, can you suggest me something to make this code faster?
Answer by deltamish · Dec 29, 2012 at 03:53 PM
Hi,Why are you calling Getcomponent three times.This affects the performence slightly I have edited your script slightly.hopefully this should you
var me:Transform;
function Awake(){
me = transform;///Cache transform so that unity doesn't have to check for it every frame
}
function OnTriggerStay (other : Collider) {
if(other.gameObject.tag == "Player"){
var player : GameObject;
if(!player)
player = other.gameObject;
if(!found){
var dir : Vector3 = player.transform.position - transform.position;
me.Translate(dir.normalized * Time.deltaTime * 15 * (1/dir.magnitude*2));
}
if(dir.magnitude < 1){
if(!found)
player.SendMessage("AddEnergy",energy);
found = true;
gameObject.light.enabled = false;
if(isPowerup){
particleSystem.loop = false;
var otgt:playercontroller;
if(!otgt)///call it only once
otgt = other.GetComponent(playercontroller) as playercontroller;
otgt.bullet_speed += bullet_factor;
otgt.speed += speed_factor;
otgt.reload_speed -= reload_factor;
}
else
{
gameObject.renderer.enabled = false;
}
yield new WaitForSeconds(2.5);
Destroy(gameObject);
}
}
}
This helped but didn't solve the problem, still the game goes really slow somehow.
do you have any script other than this.Are you using high poly models?. See the profiler it helps to know where the problem lies
Answer by Ben Ezard · Dec 29, 2012 at 03:16 PM
Might be something to do with having "yield" in the function? Just use Destroy(gameObject, 2.5) instead - it does the same thing
Your answer
Follow this Question
Related Questions
Android Bundle Version and Bunde Version Code? 0 Answers
Creating a Game for IPhone/Android but testing it on a P.C. 1 Answer
How to move 2D textures? 0 Answers
Tilt control for jump 0 Answers
Android/iOS Thumbstick Code help 4 Answers