Declaring camera on Update() and tilted camera

Hi, I have a question about declaring camera on Update method.

  1. Is declaring camera on Update() a good practice? isn’t this method running every frame like 60 times a second?
    Would it be a better practice to somehow declare camera outside Update() so it runs only once?

  2. Also, the code below works fine with no camera tilting. I haven’t used localRotation yet and I see no need to use localRotation.

I’m on Unity 5.4(I know I should have used older version - maybe something has happened with newer version?)

void Update () {


	float rotationSpeed = 6.0f;
	float mouseX = Input.GetAxis ("Mouse X")*rotationSpeed;
	float mouseY = Input.GetAxis ("Mouse Y")*rotationSpeed;
	transform.rotation *= Quaternion.Euler (0,mouseX,0);

	Camera camera = GetComponentInChildren<Camera> ();
	camera.transform.rotation *= Quaternion.Euler (-mouseY,0,0);
}

Cheers,
H

I think you are right, we shouldn’t declare the camera in the Update().
I’m also using 5.4 and I also don’t have issues with tilting with the simple rotation() method. However my camera only works if I use an array, since GetComponentInChildren() returns a Camera[].
Anyone has this issue?

Here is my working solution:

Camera[] camera;

// Use this for initialization
void Start () {
    camera = GetComponentsInChildren<Camera> ();
}

// Update is called once per frame
void Update () 
{
    float rotationSpeed = 3.0f;
    float mouseX = Input.GetAxis ("Mouse X") * rotationSpeed;
    float mouseY = Input.GetAxis ("Mouse Y") * rotationSpeed;

    transform.rotation *= Quaternion.Euler (0, mouseX, 0);

    camera[0].transform.rotation *= Quaternion.Euler (-mouseY, 0, 0);
}

Edit: I had to use arrays because I used GetComponentsInChildren instead of GetComponentInChildren… Problem solved :smiley:

Privacy & Terms