Hi all,
I’m currently following a tutorial (by the c sharp accent youtube channel) to create a first person controller. The issue I’m having that in the camera script it gives me a null reference exception. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour
{
public float turnSpeed = 1.5f;
public float turnSmoothing = .1f;
public float tiltMax = 75f;
public float tiltMin = 45f;
private float lookAngle;
private float tiltAngle;
private float smoothX = 0;
private float smoothY = 0;
private float smoothXvel = 0;
private float smoothYvel = 0;
Transform pivot;
Transform cam;
PlayerInput plInput;
public bool addShake;
public float shakeAmountX = 0;
public float shakeAmountY = 0;
// Use this for initialization
void Start ()
{
cam = Camera.main.transform;
pivot = cam.parent.parent.transform;
Cursor.lockState = CursorLockMode.Locked;
plInput = GetComponent<PlayerInput>();
lookAngle = 260;
}
// Update is called once per frame
void Update ()
{
HandleRotationMovement();
}
void HandleRotationMovement()
{
float x = plInput.mouseX;
float y = plInput.mouseY;
/*if(addShake)
{
x += shakeAmountX;
y += shakeAmountY;
}*/
if (turnSmoothing > 0)
{
smoothX = Mathf.SmoothDamp(smoothX, x, ref smoothXvel, turnSmoothing);
smoothY = Mathf.SmoothDamp(smoothY, y, ref smoothYvel, turnSmoothing);
}
else
{
smoothX = x;
smoothY = y;
}
lookAngle += smoothX * turnSpeed;
transform.rotation = Quaternion.Euler(0f, lookAngle, 0f);
tiltAngle -= smoothY * turnSpeed;
tiltAngle = Mathf.Clamp(tiltAngle, -tiltMin, tiltMax);
pivot.localRotation = Quaternion.Euler(tiltAngle, 0, 0);
}
}
Also here is the playerinput script it is referencing:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour {
public float mouseX;
public float mouseY;
public float horizontal;
public float vertical;
public bool fire1;
public bool fire2;
public bool fire3;
void FixedUpdate()
{
mouseX = Input.GetAxis("Mouse X");
mouseY = Input.GetAxis("Mouse Y");
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
fire1 = Input.GetButton("Fire1");
fire2 = Input.GetButton("Fire2");
fire3 = Input.GetButton("Fire3");
}
}
So at line 48 of the camera control script its giving me the null reference exception (object reference is not set to an instance of an object and I’m not sure its giving me that error because the movement with the wasd keys works fine just not the rotation. Also the hierarchy for the setup is as follows. I hope I explained it clear enough any help would be appreciated.