Getting a strange NullReferenceException

I’m getting a NullReferenceException in this script

public class ContainerBehaviour : MonoBehaviour
{
	
	private TouchControl touchControl;
	
	public void DropZoneStartPos()
	{
		touchControl = new TouchControl();
		
		if( gameObject.layer == LayerMask.NameToLayer( "Upper Container" ) )
		{
			
			if( gameObject.transform.position.x == touchControl.dropZoneArr[0].transform.position.x )
			{	
				
				touchControl.dropZoneArr[0].transform.position = new Vector2( gameObject.transform.position.x, gameObject.transform.position.y + 2.5f );
				Debug.Log(touchControl.dropZoneArr[0].transform.position);
			}
		}
	}
	
	void OnTriggerEnter( Collider other )
	{
		
		if( other.gameObject.layer == LayerMask.NameToLayer( "Upper Container" ) && other.transform.position.y > gameObject.transform.position.y &&
			other.gameObject.tag != "Drop Zone" )
		{
			
			gameObject.layer = LayerMask.NameToLayer( "Lower Container" );
		}
	}

}

The NullReferenceException is on this line: if( gameObject.layer == LayerMask.NameToLayer( “Upper Container” ) )

This script is attached to many game objects that either have a “Lower Container” layer or a “Upper Container” layer attached to them. I manually attach the layers in the editor. When the game starts another script references this script and the error occurs.

What I find really strange is that there is no problem when the OnTriggerEnter() runs on this line: if( other.gameObject.layer == LayerMask.NameToLayer( “Upper Container” )

Does anybody have an idea of what is happening?

Thanks in advance.

Usually, you get a NullReferenceException when you are trying to access a member with . on an object, when the object is null, like this explains.

That line that was pointed out to you by the compiler is pretty solid, especially since gameObject can’t be null, and neither can layer since Unity makes sure that a layer has to be specified.

I think maybe it has nothing to do with that line, but the code surrounding it. The only line I see directly surrounding it that is dereferencing an object is this one:

gameObject.transform.position.x == touchControl.dropZoneArr[0].transform.position.x

Again, gameObject has to exist, and so does transform, position, and x, since those define a bare-bones game object.

So mostly likely, that leaves these two guys: touchControl, dropZoneArr[0], but touchControl is defined right above!, so it’s gotta be dropZoneArr[0].

Since you are not getting an IndexOutOfRangeException (explained here), can’t be because your container is empty.

I guarantee you its because the first element of dropZoneArr is null, or something bad is happening in TouchControl’s constructor.

Print them out right before that if statement to see which one is your problem child:

Debug.Log(gameObject.name + "\'s dropZoneArr[0]: " + touchControl.dropZoneArr[0]);

if( gameObject.transform.position.x == touchControl.dropZoneArr[0].transform.position.x )