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). :slight_smile:

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.

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.