Search code examples
c#unity-game-enginecollision-detectionraycasting

Unity - Make crosshair appear when hovering over object


I've been at this for a few hours, I'm trying to make it so when shooting a raycast and it collides with an object with a certian tag, the crosshair is enabled, and if not hitting the object with the tag, it goes away. It appears to be a lot harder than I expected and I'm getting weird results.

either the cross hair appears if I click first, or it does work and the crosshair just won't disable again. Here is the code to the object interaction script. Please, let me know what I am doing wrong, thank you!

    public Collider clickObject;
    public Animator m_Animator;

    [SerializeField] public GameObject Crosshair;

    private Ray _ray;
    private RaycastHit _hit;
    private bool _opened;

    void Start()
    {
        m_Animator = gameObject.GetComponent<Animator>();
        Crosshair.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Click();
        }
    }

    private void Click()
    {
        if (!clickObject) return;
        if (!m_Animator) return;

        _ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(_ray, out _hit))
        {
            if (_hit.collider.CompareTag("InteractObject"))
            {
                Crosshair.SetActive(true);
            }
            else
            {
                Crosshair.SetActive(false);
            }

            if (_hit.collider == clickObject)
            {
                if (_opened)
                {
                    m_Animator.SetBool("isOpen", true);
                    _opened = false;
                }
                else
                {
                    m_Animator.SetBool("isOpen", false);
                    _opened = true;
                }
            }
        }
    }
}

Solution

  • Well it seems you only raycast and update your cross-hair in your Click() function which you only call when you press your left mouse button:

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                Click();
            }
        }
    

    I think you want to call it every frame instead if you want the cross-hair to appear and disappear without any user input.