Search Unity

Object reference not set to an instance of an object PlayerCamera.CameraMovement ()

Discussion in 'Scripting' started by YoloJoe, Feb 8, 2016.

  1. YoloJoe

    YoloJoe

    Joined:
    Jan 20, 2016
    Posts:
    109
    Hey again.
    I cant get this mouse look script to work. Im not getting any compile error, but errors when I play the game. Here is the code:

    Code (csharp):
    1. public void CameraMovement()
    2.     {
    3.         if (playerController.aim)
    4.         {
    5.             Camera.main.fieldOfView = Mathf.Lerp (Camera.main.fieldOfView, zoomFOV, _deltaTime * lerpSpeed);
    6.  
    7.             _camDir = (aimDirection.x * target.forward) + (aimDirection.z * target.right);
    8.             _targetHeight = normalAimHeight;
    9.             _targetDistance = normalAimDistance;
    10.         }
    11.         else
    12.         {
    13.             Camera.main.fieldOfView = Mathf.Lerp (Camera.main.fieldOfView, normalFOV, _deltaTime * lerpSpeed); // error here!
    14.  
    15.             _camDir = (normalDirection.x * target.forward) + (normalDirection.z * target.right);
    16.             _targetHeight = normalAimHeight;
    17.             _targetDistance = normalAimDistance;
    18.         }
    the error says:
    Code (csharp):
    1.  
    2. NullReferenceException: Object reference not set to an instance of an object
    3. PlayerCamera.CameraMovement () (at Assets/Scripts/PlayerCamera.cs:185)
    4. PlayerCamera.LateUpdate () (at Assets/Scripts/PlayerCamera.cs:141)
    5.  
    If anyone knows whats wrong here, please tell me.

    Thanks.
     
  2. domkia

    domkia

    Joined:
    Aug 19, 2012
    Posts:
    99
    Make sure you have plugged everything in the inspector. Could you show us the whole script?
     
  3. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Are you sure it's the line you commented? The only reference there is Camera.main, which is usually only null if the engine cannot find a camera tagged MainCamera.

    Otherwise, target might be null.

    You can simply add lines for the camera and target:

    Code (CSharp):
    1. Debug.Log("Camera: " + (Camera.main == null));
    and
    Code (CSharp):
    1. Debug.Log("Target: " + (target == null));
    respectively, each before you first use them (before you try to access a member of them).

    The other ones, except playerController which is quite a bit away from the line the error has occured, seem to be primitive types so go for the both i mentioned above.

    Hint: you're using lerp incorrectly, maybe intentionally, maybe not.
     
  4. YoloJoe

    YoloJoe

    Joined:
    Jan 20, 2016
    Posts:
    109
    I fixed it by using
    Code (csharp):
    1. public Camera theCam;
    and then using
    Code (csharp):
    1. theCam.fieldOfView=Mathf.Lerp(Camera.main.fieldOfView, normalFOV, _deltaTime * lerpSpeed);
    Thanks anyways guys ;)