NullReferenceException: Object reference not set to an instance of an object - Don't know why
I have this script (see below) and i keep getting errors on lines 19, 20, 24, and 25, but why?
using UnityEngine;
using System.Collections;
public class CameraControll : MonoBehaviour {
public Vector3 RotateSpeed;
public GameObject Camera;
public float MinDistance;
public float MaxDistance;
public float ZoomSpeed;
Transform black;
Transform white;
// Update is called once per frame
void FixedUpdate ()
{
if (GameController.WhiteTurn)
{
Camera.transform.position = white.position;
Camera.transform.rotation = white.rotation;
}
if (!GameController.WhiteTurn)
{
Camera.transform.position = black.position;
Camera.transform.rotation = black.rotation;
}
if (Input.GetKey(KeyCode.RightArrow))
{
gameObject.transform.Rotate(-RotateSpeed);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
gameObject.transform.Rotate(RotateSpeed);
}
if (Input.GetKey(KeyCode.UpArrow) && Vector3.Distance(Camera.transform.position, gameObject.transform.position) >= MinDistance)
{
Camera.transform.position += Camera.transform.forward * ZoomSpeed;
}
if (Input.GetKey(KeyCode.DownArrow) && Vector3.Distance(Camera.transform.position, gameObject.transform.position) <= MaxDistance)
{
Camera.transform.position += -Camera.transform.forward * ZoomSpeed;
}
if (GameController.WhiteTurn)
{
white = Camera.transform;
}
if (!GameController.WhiteTurn)
{
black = Camera.transform;
}
}
}
Answer by Bonfire-Boy · Sep 29, 2016 at 12:13 AM
The first time FixedUpdate is called, you haven't assigned anything to white
and black
yet, so they're null. Try moving the last bit of FixedUpdate, where you set them, to the start of the function.
But from what you've shown, it's not clear what the point of the white
and black
variables is. Since you only ever set them to Camera.transform
you could use that instead. This would make it clear that your troublesome lines, even when they do work, will do nothing (`Camera.transform.position = Camera.transform.position`).
I think probably you're trying to use white
and black
to cache the transform's position and rotation at certain times, in which case it won't work because they just point to the transform. Their position/rotation will always be the camera's position/rotation because they are the camera's transform, not copies of it. To save those values you should cache Camera.transform
's position and rotation (which are value types so you will get copies, the values of which won't change when the camera then moves).
Thanks, I didn't even realize they were null in the first update!