Search code examples
c#unity-game-engineraycasting

Getting objects name by pointing on it Unity Raycast


I want to print name of object witch i am pointing on (with crosshari). I wrote some scripts witch allows me to highlight object by looking at it (included below). Can you tel me how can i add a line of code doind this (print name of object witch i am pointing on)?

1.SelectionManager

`public class SelectionManager : MonoBehaviour
{
    [SerializeField] private string selectableTag = "Selectable";

    private ISelectionResponse _selectionResponse;

    private Transform _selection;

    private void Awake()
    {
        _selectionResponse = GetComponent<ISelectionResponse>();
    }

    private void Update()
    {
        if (_selection != null) _selectionResponse.OnDeselect(_selection);

        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        _selection = null;
        if (Physics.Raycast(ray, out var hit))
        {
            var selection = hit.transform;
            if (selection.CompareTag(selectableTag) || (selection.CompareTag("Stool_square1")))
            {
                //string name = gameObject.name;
                //print(name);
                _selection = selection;
            }
        }

        if (_selection != null) _selectionResponse.OnSelect(_selection);
    }
}`

2.OutlineSelectionResponse

using UnityEngine;

public class OutlineSelectionResponse : MonoBehaviour, ISelectionResponse
{
    public void OnSelect(Transform selection)
    {
        var outline = selection.GetComponent<Outline>();
        if (outline != null) outline.OutlineWidth = 2;
    }

    public void OnDeselect(Transform selection)
    {
        var outline = selection.GetComponent<Outline>();
        if (outline != null) outline.OutlineWidth = 0;
    }
}

3.ISelectionResponse

using UnityEngine;

internal interface ISelectionResponse
{
    void OnSelect(Transform selection);
    void OnDeselect(Transform selection);
}

Solution

  • try some thing like hit.collider.name