clicking a object

I’m kind of new to unity and am creating a game that involves clicking a object to break it and ray casts just send the ray to the center of the screen
my code:

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

public class ClickManager : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.MousePosition);
            Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

            RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
            if (hit.collider != null)
            {
                Debug.Log(hit.collider.gameObject.name);
                destroy(this);
            }
        }
    }
}

help would be appreciated as I have been stuck on this for a week.

Your raycast has no direction being Vector2.zero. This will always return no results.

This is also the wrong way to do mouse picking in 2D. There is no real depth in 2D so we just check the world position of the mouse.

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D hit = Physics2D.OverlapPoint(mousePos);
2 Likes

should I put the script on the object I want to destroy?
also thx

No, it should be on it’s own object or attached to the player object.

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D hit = Physics2D.OverlapPoint(mousePos);

if (hit != null)
{
    Destroy(hit.gameObject);
}

thank you but I want it to only break a specific block with a tag.

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D hit = Physics2D.OverlapPoint(mousePos);

if (hit != null && hit.CompareTag("TagToDestroy"))
{
    Destroy(hit.gameObject);
}

also it still puts it at the center of the main camera

also any chance you can make it avoid the player

I don’t understand what you mean by that, nothing in the code moves or puts anything anywhere.

The code avoids anything that doesn’t have the tag following my third posts code.

@person90111 People arent going to write entire code for you (unless you’re really lucky). As Chris mentions, the code doesnt do anything with the object except destroy the object. If you read the code he provided, you would see that it:
Assigns a Vector3 (X, Y, Z) called mousePos to be where the mouse is, assigns a Collider2D called hit that is at the mousePos location. Then, if the hit is NOT null and has the Tag “TagToDestroy”, it will destroy the hit object.