- Home /
Testing if object is null creates a NullReferenceException.
Hello, I want to access an object from a component which I purposefully set to null in the constructor (Start()). It is part of a doubly linked list, and as such the first and last objects will be null. The problem is so... ridiculous. When accessing the object to test if it is null, I get a NullReferenceException. Is there any way to fix that (please say yes). :)
void LateUpdate()
{
// Call the follow script on children after we have moved.
GameObject child = GetComponent<Attach>().myChild;
if (child != null)
child.GetComponent<Attach>().followParent();
}
It will throw the error on the first GetComponent line.
GetComponent() might be returning null.
Try this: GameObject child = GetComponent() if(child != null) child = child.myChild; if (!child) return;
Answer by robertbu · Aug 14, 2014 at 05:12 PM
The problem is that this:
GetComponent<Attach>()
...is failing to find the 'Attach' component on the same game object with this script. Most likely reasons based on similar questions on this list:
The 'Attach' script is on another game object
The 'Attach' script was never attached to this game object
You have the above script on multiple game objects, but at least one does not have the 'Attach' script.
Bang on! The component was in a child of my Player... I forgot that. Thank you very much!
Your answer
Follow this Question
Related Questions
NullReferenceException MaskableGraphic.UpdateCull() upon Loading Player Data. 0 Answers
Why is my array null? 0 Answers
Instantiate gameObject returns null? 1 Answer
Need Help With a NullReference Exception 2 Answers
Enemy not giving damage 2 Answers