NullReferenceException

I searched the forum and found some threads about NullReferenceException but do not understand how i can fix this in my code.

I have three cameras (StartCamera, MainCamera, EndCamera) and in this script:

var camera1 : GameObject;
var camera2 : GameObject;
var camera3 : GameObject;

function Start () {
camera1.camera.enabled = false;
camera2.camera.enabled = true;
camera3.camera.enabled = false;
}

function Update () {
if (Input.GetKeyDown (“2”)){
camera1.camera.enabled = true;
camera2.camera.enabled = false;
camera2.camera.enabled = false;
}
if (Input.GetKeyDown (“1”)){
camera1.camera.enabled = false;
camera2.camera.enabled = true;
camera2.camera.enabled = false;
}
if (Input.GetKeyDown (“3”)){
camera1.camera.enabled = false;
camera2.camera.enabled = false;
camera2.camera.enabled = true;
}
}

i can change the actual camera via push the 1, 2 or 3 key.

In a script wich control the player (a ball) there is this line (line 17):

var forward = Camera.main.transform.TransformDirection(Vector3.forward);

and the NullReferenceException come from this line.

So how can i fix the problem?

Until now the program is working even with the error.
When i use the StartCamera or the EndCamera i can not stear the ball but that is ok.
When i use the MainCamera again i can stear the ball again.

I dont’t know if i can let the error be there but i want to have clean code.

Here is the line from the Console:
NullReferenceException: Object reference not set to an instance of an object
BallRolling.FixedUpdate () (at Assets\Mr Big Ball Assets\MyScripts\BallRolling.js:17)

I would guess that it is coming from the fact that the main camera is disabled. Camera.main returns you the main camera in the scene, and perhaps when it is disabled it throws a null reference exception? You can try removing the main i.e. just Camera.transform… and hope that this will give you the active camera in the scene…

Hello,

if you enabled other camera than the main camera, I think that’s where your null exception is coming.

I think you can only use one main camera named “main”.

maybe if you tell Unity that the main camera is the one that’s enabled

Hope that helps,
Ray

Edit: ivkoni’s answer makes more sense :smile:

:smile: I was just about to edit my response, since I don’t think it will work. If you have a camera attached to your game object then you could access it with just camera. Otherwise you need to use allCameras, main or current. I would think allCameras or current is what you want in this case, but not sure, and I can’t test out it now since I am at work. Hopefully somebody else will give you a more definite answer :slight_smile: I didn’t quite get the “current” camera description from the doc.