How do i find the object hit by a Raycast.

I’m trying to make a grid lock building system. I have it where it sends out a ray cast from the mouse’s position when it is click to get the spot to place the block. But, i can find the center of the object hit to find what side it should offset the placed block on.
So, i’m asking how do i find an object using a Raycast?

(If you need the script to answer then I’ll send it and thx)

so code first…

Check this out Unity - Scripting API: Camera.ScreenToWorldPoint

*Add this class to any gameobject.

*Create the tag “AnyTag” (or any other name) and assign it to the gameobject that you want to find.

*Create a layer and assign it to the gameobject that you want to find.

*Assign that same layer to the property WhatCanIHit of the gameobject with this class.

*Make sure that the gameobject that you want to find has a collider.

*Hit Play and click on top of the gameobject to see the Debug.Log on the console.


using UnityEngine;

public class FindRaycastObject : MonoBehaviour
{
    // The object that you want to find with the raycast should
    // have the same layer as this LayerMask. Make sure that the gameobject that
    // has this class attached doesn't have this Layer assigned.
    [SerializeField] private LayerMask WhatCanIHit = 1;

    private Camera _Camera;

    private void Awake()
    {
        // Store camera for better performance.
        _Camera = Camera.main;
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = _Camera.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out RaycastHit hit, 100, WhatCanIHit))
            {
                if (hit.collider != null)
                {
                    // Add a tag to your object and use use CompareTag for better performace.
                    if (hit.collider.CompareTag("AnyTag"))
                    {
                        Vector3 objPosition = hit.transform.position;
                        Vector3 objColliderCenter = hit.collider.bounds.center;
                        Debug.Log($"Found: {hit.transform.name} | Position: {objPosition} | ColliderCenter: {objColliderCenter}");
                    }
                }
            }
        }
    }
}