当 Raycast 在 Unity C# 中移开时停用游戏对象上的脚本

Deactivate script on game object when Raycast moves away in Unity C#

我试图在 Raycast 未命中时禁用游戏对象上的 component/script,但在命中时启用它。我可以启用脚本,当 Raycast 命中时该部分工作,但是,当我离开对象时,它仍然启用,我似乎无法弄清楚这一点。 执行此操作的完整代码在我的更新函数中。

// Update is called once per frame
 void Update()
 {
     Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
     float distance = 100f;
     Debug.DrawRay(ray.origin, ray.direction * distance, Color.green);
     RaycastHit hit;
     if (Physics.Raycast(ray, out hit))
     {
        
         // hit!
         Debug.Log("Raycast is hitting " + hit.transform.gameObject);

         if (hit.transform.tag == "Crate")
         {
             crossair.color = Color.red;

             hit.transform.GetComponent<Outline>().enabled = true; // this works

         }

         else
         {
             crossair.color = Color.white;
             hit.transform.GetComponent<Outline>().enabled = false;  //Does not work
         }           
     }

 }

您将需要存储当前激活的,以便在万一

时停用它
private const float distance = 100f;

private Outline currentHit;

void Update()
{
     var ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));

     if (Physics.Raycast(ray, out var hit))
     { 
         // hitting something

         // Actually checking this way makes you tag redundant ;)
         if (hit.transform.TryGetComponent<Outline>(out var outline))
         {
             // Hitting and outline!

             Debug.DrawLine(ray.origin, hit.point, Color.red);

             if(outline != currentHit)
             {
                 // Hitting a different outline!
                 crossair.color = Color.red;

                 if(currentHit)
                 {
                     currentHit.enabled = false;
                 }
                 currentHit = outline;
                 currentHit.enabled = true; 
             }
         }
         else
         {
             // Hitting something that is not an outline

             crossair.color = Color.white;
             Debug.DrawLine(ray.origin, hit.point, Color.green);
             
             if(currentHit)
             {
                 currentHit.enabled = false;
                 currentHit = null;
             }
         }
     }
     else
     {
         // Not hitting anything

         crossair.color = Color.white;

         Debug.DrawRay(ray.origin, ray.direction * distance, Color.green);
             
         if(currentHit)
         {
             currentHit.enabled = false;
             currentHit = null;
         }
     }
}