Search code examples
c#unity-game-engineonmouseoverraycastinggameobject

Raycast hit game object in unity


I created a 3d main menu in unity, each button is a cube. I enabled the user to press on the button by raycast hit, the problem is that I want to change the cube color when the raycast is on the cube and convert it back to the original color when the raycast exit the cube. I'm using c# and I read about "OnMouseEnter" and "OnMouseExit" - I'm not using a mouse but using game controller (Razer Hydra). How can I simulate OnMouseEnter and OnMouseExit in raycast?


Solution

  • From what i understand you want to raycast on the cube and change its color and change it back when the cursor or ray cast is not hitting it, I would suggest using this logic without mouseEnter and mouseExit.

    RaycastHit hit;

    void Update () {
    
       Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
       if (Physics.Raycast(ray, out hit)) {
          if (hit.collider.tag == "cube"){
            //Change color here
            }
    
        }else {
    
        // Change back to prvious color.
    

    } }