How to find the object that the linecast hits?

Hello. I want to destroy the tree that the linecast hits when I press “E”. How do I do that? This is in 2D!

        Debug.DrawLine(transform.position, treeSight.position, Color.black);
		nearTree = Physics2D.Linecast(transform.position, treeSight.position, 1 << LayerMask.NameToLayer("Tree"));

		if (Input.GetKeyDown (KeyCode.E) && nearTree == true) {
			Destroy(//What do I put in here?);
		}

You need to set linecast variable from the output of the linecast

hit = Physics2D.Linecast(transform.position, treeSight.position, 1 << LayerMask.NameToLayer("Tree"))) {

if (hit.collider != null)
     Destroy(hit.collider.gameObject);

Notice hit = , define RaycastHit2D hit before calling this function. It will store hit information you need. Also, you can simply create a variable of type LayerMask and select your trees layer there. And use it as the mask. It makes things easier when dealing with multiple layers.

Hi

Detecting a hit on a collider is not done using LineCast but achieved using RayCasting. However, in 2D there’s a few things to keep in mind :

  1. Raycasting from a gameobject will not ignore its own 2D collider
  2. Raycasting does not “draw” a line, it merely casts one to detect collision. If you want to visualize it you can use Debug.DrawRay()
  3. The object you want to “hit” during the raycast must have a 2D collider

Here’s an example:

void Update() {
    // Disable the object's own collider to avoid a false-positive hit
    // Remove this if your object doesn't have a collider
    collider2D.enabled = false;

    // Raycast for a hit in the forward direction at a maximum distance of 100 units
    RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector3.forward, 100f, 1 << LayerMask.NameToLayer("Tree"));

    // Re-enable the object's own collider
    // Remove this if your object doesn't have a collider
    collider2D.enabled = true;

    // Visualize the ray for debugging purposes
    Debug.DrawRay(transform.position, Vector3.forward * 100f, Color.magenta);

    // Report the hit to the console
    if (hit.collider != null) {
        print(hit.collider.name + " is in front of " + gameObject.name);

        // To destroy the object you hit you can uncomment the line below
        //
        // Destroy( hit.collider.gameObject );
        //
    }
}

nearTree.collider.gameObject