Home > OS >  Panel activated/deactivated by Raycast, Deactivation not working
Panel activated/deactivated by Raycast, Deactivation not working

Time:07-07

Hiya I wrote this code and am having issues with deactivating my panel when the raycast hovers away. Works perfectly when hovering over. I have no idea how to fix this error. Thanks in advance

public Ray handRay;
private RaycastHit hit;
public GameObject myPanel;


void FixedUpdate()
{
    RaycastHit hit;
    Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
    Debug.DrawRay (transform.position, forward, Color.green);

    if (Physics.Raycast(transform.position, (forward), out hit))
    {
        if (hit.collider.tag == "Head")
        {
            myPanel.SetActive(true);
        }
        else if (hit.collider.tag != "Head")
        {
            myPanel.SetActive(false);
        }
    }
}

CodePudding user response:

Fixed- for anyone wanting to implement this

public class RayCastPanelActive : MonoBehaviour {

public Ray handRay;
private RaycastHit hit;
public GameObject myPanel;


void FixedUpdate()
{
     RaycastHit hit;
     Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
        //Debug.DrawRay (transform.position, forward, Color.green);

     if (Physics.Raycast(transform.position, (forward), out hit))
     {

         if (hit.collider.tag == "Head")
         {
            myPanel.SetActive(true);
            print(hit.collider.gameObject.name);
             
         }

     }
    else
         {
             myPanel.SetActive(false);
         }
        
    
         
}

}

CodePudding user response:

Put a debug statement inside both your if and else. That way you will know what you are hitting with your Raycast.

Also like BugFinder says you want only else.

CodePudding user response:

It looks like you figured it out, but for anyone else who hits this problem, Unity's behavior inside a failed raycast has changed over the years.

These days, you should also be able to check hit for a null.

And Hit.collider should be throwing an error if hit is null.

Checking the result of the Physics.Raycast is the way to go though.

  • Related