- Home /
Unity spammed with NullReferenceExceptions
I have a script to always parent an object to the current camera and set its local position to that of the camera. The script works fine, however the console is spammed with NullReferenceExceptions occurring on line 7 of the script. This makes it very annoying and difficult to find true errors.
Here is the script:
using UnityEngine;
using System.Collections;
public class MoveToCam : MonoBehaviour {
void Update () {
transform.localPosition = new Vector3 (0, 0, 0);
transform.parent = Camera.current.transform;
}
}
Answer by Rtyper · May 10, 2015 at 08:45 PM
Setting transform.parent is something you only need to do once. After that, it's a child of the other object so it will stay in the same place relative to the parent object. You'd be better off doing this in Start rather than Update. That's why it keeps coming up.
The null reference exception itself means that Camera.current is null. Make sure your camera is tagged as MainCamera, that's what determines Camera.current.
The problem is, the current camera is constantly changing. Pressing shift switches the camera to another one, so I have to keep it in update for the parenting to function correctly.
Why don't you keep a reference to the script and each time you switch cameras, the new one is assigned to a variable in the script.
Answer by MANDAL0R3 · May 10, 2015 at 10:19 PM
Camera.Current is returning null at some points of the call. Normally when i run across this error it means that something that is trying to be accessed is null. To fix the problem just add this new line of code and it should all work fine.
using UnityEngine;
using System.Collections;
public class MoveToCam : MonoBehaviour{
void Update(){
transform.localPosition = new Vector3(0, 0, 0);
if (Camera.current != null)
{
transform.parent = Camera.current.transform;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613195304im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Got a Error about reffering a object i can not fix 0 Answers
NullReferenceException and m_InstanceID == 0 on LoadLevel (C#) 1 Answer