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

Time:03-19

I am trying to disable a component/script on a game object when the Raycast has not hit but enable it when it does hit. I can enable the script and that part works when the Raycast hits, however, when I move away from the object, it is still enabled and I cant seem to figure this out. The entire code to do this is in my update function.

// 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
         }           
     }

 }

CodePudding user response:

You will need to store the currently active one in order to deactivate it in case

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;
         }
     }
}
  • Related