Hi,
First time posting here. I have seen this error in multiple threads, but still haven’t found a solution to my problem, and I didnt want to hijack other threads, so:
Doing a top down game where you will walk with WASD and aim/look with mouse, was working but now I’m getting:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.ControlMouse () (at Assets/Scripts/PlayerController.cs:35)
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:27)
Im checking the referenced objects on 35 and 27, still cant find it, if anyone has a clue, Id be really grateful, thanks!
Heres the script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour {
//Handling variables
public float rotationSpeed = 450; //360 så ett varv per sekund
public float walkSpeed = 5;
public float runSpeed = 8;
//System variables
private Quaternion targetRotation;
//Components
private CharacterController controller;
private Camera cam; //För mouse-styrningen
void Start() {
controller = GetComponent<CharacterController>();
cam = Camera.main;
}
void Update () {
ControlMouse();
//ControlWASD();
}
void ControlMouse() {
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x,0,transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, rotationSpeed * Time.deltaTime);
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")); //GetAxisRaw accelererar inte, snapp speed (?)
Vector3 motion = input;
motion *= (Mathf.Abs(input.x) == 1 && Mathf.Abs(input.z) == 1) ? .7f : 1;
motion *= (Input.GetButton("Run")) ? runSpeed : walkSpeed;
motion += Vector3.up * -8; //gravity
controller.Move(motion * Time.deltaTime);
} }