Apologies if this is glaringly obvious or if i’m posting in the wrong place.
For context: I’m new to Unity and scripting and am attempting to follow some tutorials to script my own basic movement rather than use Unity’s premade assets. I’m following Quill’s FPS tutorial (Link)…
As far as I can tell my script is as identical to tutorial as possible (although i admit i’m probably mistaken on this). I’m receiving the error ‘Object reference not set to an instance of an object’ every time i try and test the game. Unity refers me to line 37 of my script…
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (CharacterController))]
public class FirstPersonController : MonoBehaviour {
public float movementSpeed = 5.0f;
public float mouseSensitivity = 5.0f;
float verticalRotation = 0;
public float upDownRange = 60.0f;
public float jumpSpeed = 20.0f;
float verticalVelocity = 0;
CharacterController characterController;
// Use this for initialization[/I]
void Start () {
//Screen.lockCursor = true;
//Cursor.visible = false;[/I]
CharacterController characterController = GetComponent<CharacterController>();
}
// Update is called once per frame[/I]
void Update () {
//Rotation [/I]
float rotLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity;
transform.Rotate (0, rotLeftRight, 0);
verticalRotation -= Input.GetAxis ("Mouse Y") * mouseSensitivity;
verticalRotation = Mathf.Clamp (verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler (verticalRotation, 0, 0);
//Movement [/I]
float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
verticalVelocity += Physics.gravity.y * Time.deltaTime;
if (characterController.isGrounded && Input.GetButtonDown ("Jump")) {
verticalVelocity = jumpSpeed;
}
Vector3 speed = new Vector3 (sideSpeed, verticalVelocity, forwardSpeed);
speed = transform.rotation * speed;
characterController.Move (speed * Time.deltaTime);
}
}
If anyone can give me any direction I’d really really appreciate it. I’ve wracked my brain for a solution for the last few hours but can’t figure out where i’ve gone wrong. Thanks in advance!
Could the discrepency between what works in my project and what worked in the tutorial be because the tutorial used an older version of Unity? Or must I have made some sort of mistake whilst following his directions? (As in the tutorial the script definitely reads…
Honestly, I’m not sure, if it was due to bad coding, an old Unity version or if there are simply multiple ways on how to achieve this Apparently, you could also just put this line from your posting into the “void Update” without having the variable and the code-bit from the “void Start” and it will work.