NullReferenceException: Object reference not set to an instance of an object

I have a script that gives and error on line 18

NullReferenceException: Object reference not set to an instance of an object

but I don’t know which object is missing due to lack of clarity.heres my script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class treecontroller : MonoBehaviour {

	public Vector3 startpos;

	// Use this for initialization
	void Start () {		
	}
	
	// Update is called once per frame
	void Update () {
		startpos = new Vector3 (transform.position.x, transform.position.y - 10);

		RaycastHit2D hit2d = Physics2D.Raycast (startpos,Vector2.down);
//this is the dodgy line 
        gameObject.transform.position = new Vector3(gameObject.transform.position.x, hit2d.collider.gameObject.transform.position.y);
	}
}

Do this:

if(hit2d.collider != null)
{
   gameObject.transform.position = new Vector3(gameObject.transform.position.x, 
   hit2d.collider.gameObject.transform.position.y);
}

the problem is, “if you are not colliding with a thing, nothing will happen”

Simply make sure the collider is not null

 RaycastHit2D hit2d = Physics2D.Raycast (startpos,Vector2.down);
  //this is the dodgy line 
  if( hit2d.collider != null )
         gameObject.transform.position = new Vector3(gameObject.transform.position.x, hit2d.collider.gameObject.transform.position.y);