I have this weird issue where the console is throwing an error saying the classic “Object reference is not set to an instance of an object”, when in fact it is.
using UnityEngine;
using System.Collections;
public class CameraMovement : MonoBehaviour {
public Transform myTransform;
Quaternion rot;
float input;
void Start () {
myTransform = GetComponentInChildren<Camera>().transform;
}
void Update () {
if(myTransform != null) {
input += -Input.GetAxis("Mouse Y") * rotSpeed;
input = ClampAngle(input, yClamp.x, yClamp.y);
rot.eulerAngles = new Vector3(input, myTransform.rotation.eulerAngles.y,myTransform.rotation.eulerAngles.z);
myTransform.rotation = rot;
myTransform.position = new Vector3(transform.position.x, col.bounds.max.y - .25f, transform.position.z);
}
}
}
It’s not breaking anything, it’s just annoying to see. Anyone else having this problem?
If Unity says the reference is null, then the reference is null, no way around it. There are no circumstances when it’s random. One common cause is that you have two instances of the script and didn’t assign the reference on one of them. Also, it’s suspicious in this case where you have a public variable that’s assigned in the inspector, but then you also assign it in the Start function; you should do one or the other but not both. GetComponentInChildren() could return null if there is no Camera component on the object or any children.
When you use public transforms and assign them in the editor, you don’t need to use GetComponent. I’m not sure if thats it or not though. Sometimes I’ve encountered this error because I pointed at a prefab instead of an object in the heirarchy and vice versa.
Thanks for the information! I made it public to make sure that something was getting assigned to it. I had it private when it first started happening. I can’t believe I didn’t think that I accidentally put it on another object, I must have been very tired yesterday. I just found the object that wasn’t supposed to have the script on it. I feel very stupid right now.