Raycast won't collide :(

I have this raycast system to make an object clickable and then call a function to activate a few things, I tried to take out those things and simply make it print something to see if it is working, but it isn’t, please help.

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

public class Holededuct : MonoBehaviour
{
    public Component bedUnlock;
    public GameObject vidPlayer;
    public int tStop;

    //I used ray2 and hit2 in the names because I already have another raycast

    Ray ray2;
    RaycastHit hit2;

    void Start()
    {
        bedUnlock.GetComponent<BoxCollider>().enabled = false;
        vidPlayer.SetActive(false);
    }

    void OnTriggerStay()
    {
        ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray2, out hit2))
        {
            if (Input.GetMouseButtonDown(0))
                holeFlashback();
        }
    }

    void holeFlashback()
    {
        bedUnlock.GetComponent<BoxCollider>().enabled = true;
        vidPlayer.SetActive(true);
        Destroy(vidPlayer, timeStop);
    }

}

Forgive me for saying that, but this code looks bad and confused.

  • Don’t put if (Input.GetMouseButtonDown(0)) in a OnTriggerStay method
  • Place all Input.* calls (like this if (Input.GetMouseButtonDown(0))) in Update (otherwise don’t expect it to work reliably)
  • You were looking for OnMouseOver, I suspect.

entertain this:

bool _isMouseOver = false;
void Update ()
{
    if( _isMouseOver && Input.GetMouseButtonDown(0) )
        HoleFlashback();
}
void OnMouseEnter ()
{
    _isMouseOver = true;
}
void OnMouseExit ()
{
    _isMouseOver = false;
}

Just Replace Physics.Raycast(ray2 , out hit2):
With Physics.Raycast(ray2.origin, ray2.direction, out hit2);