Hello, I’m trying to access the main camera, but my script is placed on my FPSController. Everytime I try and press “4” to do something with the camera it says:
MissingComponentException: There is no 'Camera' attached to the "First Person Controller" game object, but a script is trying to access it.
SPController.Update () (at Assets/Scripts/SPController.js:88)
I’m not sure what else to try and do, I’ve added the maincamera to the inspector slot. I’m not sure if I’ve missed something obvious.
var mainCamera : Camera;
var zoom : int = 20;
var normal : int = 60;
var smooth : float = 5;
if(Input.GetKeyDown("4"))
{
hawkEye = !hawkEye;
if(hawkEye == true)
{
mainCamera.fieldOfView = Mathf.Lerp(camera.fieldOfView, zoom, Time.deltaTime * smooth);
}
else if(hawkEye == false)
{
mainCamera.fieldOfView = Mathf.Lerp(camera.fieldOfView, normal, Time.deltaTime * smooth);
}
}
You have a reference to a camera, called mainCamera which you’re assigning from the inspector, everything’s fine there. But you’re trying to access the camera component that’s attached to the gameObject that this script is attached to (by calling camera), but it’s not finding it cause there isn’t any. In other words, your problem isn’t with mainCamera, but with camera. (camera always refers to the camera component of your gameObject)
And btw, if by mainCamera you mean the main camera in your scene, why not just access it via Camera.main? - Just make sure the camera has the MainCamera tag for this to work.
You’re trying to access camera.fieldOfView within the script, but the script is not attached to a camera object, so the camera variable does not exist.
Instead, you might have meant to use mainCamera.fieldOfView:
var mainCamera : Camera;
var zoom : int = 20;
var normal : int = 60;
var smooth : float = 5;
if(Input.GetKeyDown("4"))
{
hawkEye = !hawkEye;
if(hawkEye == true)
{
mainCamera.fieldOfView = Mathf.Lerp(mainCamera.fieldOfView, zoom, Time.deltaTime * smooth);
}
else if(hawkEye == false)
{
mainCamera.fieldOfView = Mathf.Lerp(mainCamera.fieldOfView, normal, Time.deltaTime * smooth);
}
}