Question by
Shadowblitz16 · Aug 31, 2016 at 10:20 PM ·
variablesavereferencemain camera
Access Main Camera and store it in a variable for quick access?
does anybody know how to store a reference of main camera into a variable without instantiating a new one?
my current code is
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class CameraSnap : MonoBehaviour {
public int X = 0;
public int Y = 0;
public int Width = 160;
public int Height = 144;
private Camera cam = GameObject.GetComponent<UnityEngine.Camera>();
private float res = Screen.width / Screen.height;
// Update is called once per frame
void Update () {
cam.orthographic = true;
cam.orthographicSize = res;
cam.pixelRect = new Rect(Screen.width - X, Screen.height - Y, Width, Height);
}
}
but I get an error of "An object reference is required for the not-static field, method, or property 'Unity.GameObject.GetComponent()'" on line 12 on the cam declaration.
Comment
Answer by doublemax · Aug 31, 2016 at 10:25 PM
If the camera is tagged "MainCamera" it can be accessed through Camera.main.