- Home /
My door causes lag spikes.
So I go to "play" my game and you can walk around in my little scene I've made... I've been experimenting with doors. Anyways I have the door working the way I want but it causes a very noticeable lag spike which leads me to believe that it's not done the right way.
using UnityEngine;
using System.Collections;
public class door : MonoBehaviour
{
private bool isDoorOpen = false;
private GameObject currentDoor;
public float doorOpen = 10.0f;
public float doorClosed = 270.0f;
public bool doorLabelOpen = false;
public double xPos = Screen.width;
public double yPos = Screen.height;
// Use this for initialization
void Start()
{
}
void OnGUI()
{
if (doorLabelOpen == true)
{
GUI.Label(new Rect(Screen.width / 2, Screen.height / 1.03f, 100, 20), "Press E.");
}
}
void OnTriggerStay(Collider other)
{
Rigidbody rb = GetComponent<Rigidbody>();
if (other.gameObject.tag == "Player")
{
Debug.Log("player is here");
doorLabelOpen = true;
if (isDoorOpen == false && Input.GetKeyDown(KeyCode.E))
{
rb.transform.eulerAngles = new Vector3(transform.eulerAngles.x, doorOpen, transform.eulerAngles.z);
isDoorOpen = true;
}
else if (isDoorOpen == true && Input.GetKeyDown(KeyCode.E))
{
rb.transform.eulerAngles = new Vector3(transform.eulerAngles.x, doorClosed, transform.eulerAngles.z);
isDoorOpen = false;
}
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
doorLabelOpen = false;
}
}
}
My code is not organized all too well, so don't mind the mess eh? What am I doing wrong? I'm just experimenting, and I'm not expecting to be spoon fed however being pointed in the right direction would be nice!
Answer by Baste · Apr 23, 2015 at 03:52 PM
So there's the general performance tip of not doing a GetComponent every frame - your rigidbody should be a private field, and get fetched on start:
RigidBody rb;
void Start() {
rb = GetComponent<Rigidbody>();
...
}
And then you remove that line from the top of OnTriggerStay.
That shouldn't cause that much noticeable lag, though. The only thing in your code I can see that might cause lag is the Debug.Log in OnTriggerStay.
It might be a supprise, but Debug.Log is quite the performance hog. It's usually okay to have one every frame, though - but I have seen algorithms that should take 1 second take 1 minute when I try to print a couple of thousand lines by mistake, so that might be it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613193848im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Walls with doors in Unity3D 1 Answer
Opening a door with a mouse click (c#) (3D) 2 Answers
How do you tigger an animation with a box collider in Unity 4? 0 Answers
Unity 4 animations 0 Answers