Horrible Lag spike when Looking at an object that's showing GUI
I have a battery pickup script that shows the text "Press E to pickup" when your looking at it. But for some reason it causes horrible lag and i don't know why. Here's the code. C#
using UnityEngine;
using System.Collections;
public class battries : MonoBehaviour {
public float a;
public float b;
public float c;
public float d;
public bool showText;
public int Bat;
public GameObject Flight;
public int mainBat;
public bool safeRemove;
void Start()
{
showText = false;
}
void OnTriggerStay(Collider other)
{
showText = true;
if (!safeRemove)
{
if (Input.GetKeyUp(KeyCode.E))
{
mainBat = Flight.GetComponent<flashlight>().batLevel;
Bat = 100;
Flight.GetComponent<flashlight>().batLevel = Bat += mainBat;
safeRemove = true;
if (safeRemove)
{
Destroy(this.gameObject);
}
}
}
}
void OnTriggerExit(Collider other)
{
showText = false;
}
void OnGUI()
{
if (showText)
{
GUI.Box(new Rect(Screen.width / 2.55f, Screen.height / 124.98f, Screen.width / 3.78f, Screen.height / 16.1f), "Press 'E' to pickup");
}
}
}
Here's an image of the profiler
Answer by tom_coursow · Oct 18, 2016 at 06:47 AM
I guess it's not related to "looking at" the gameobject. The gameobject has a trigger stay Method (which gets called ever frame if there is a collision) in which you call GetComponent multiple times. GetComponent is a expensive operation. You might want to save flashlight OnStart() to a class variable and access this there instead of using get component.
I'm sorry but i don't understand how to fix this, i'm not good at c#
using UnityEngine;
using System.Collections;
public class battries : $$anonymous$$onoBehaviour {
public float a;
public float b;
public float c;
public float d;
public bool showText;
public int Bat;
public GameObject FlightGO;
private flashlight flight;
public int mainBat;
public bool safeRemove;
void Awake() {
flight = FlightGO.GetComponent<flashlight>();
}
void Start()
{
showText = false;
}
void OnTriggerStay(Collider other)
{
showText = true;
if (!safeRemove)
{
if (Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.E))
{
mainBat = flight.batLevel;
Bat = 100;
flight.batLevel = Bat += mainBat;
safeRemove = true;
if (safeRemove)
{
Destroy(this.gameObject);
}
}
}
}
void OnTriggerExit(Collider other)
{
showText = false;
}
void OnGUI()
{
if (showText)
{
GUI.Box(new Rect(Screen.width / 2.55f, Screen.height / 124.98f, Screen.width / 3.78f, Screen.height / 16.1f), "Press 'E' to pickup");
}
}
}
I tried the code but the problem is still happening, it's better than before but it still happens
Your answer
Follow this Question
Related Questions
GameView.GetMainGameViewTargetSize() problem 0 Answers
Massive Rendering spike in profiler when unloading the scene 0 Answers
Performance issues with many objects/lights 1 Answer
Low framerate on Android devices 0 Answers
Mobile Performance Issues 0 Answers