Search Unity

Raycast hit collider issue ?

Discussion in 'Scripting' started by Quast, Nov 10, 2017.

  1. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    Hi
    I don't know why the raycast not running well when hit enemy ray1_bool turn true after the enemy moves away from the ray it not turn false !!? Here is my script.

    Code (CSharp):
    1.         RaycastHit hit2;
    2. // rays1 = gameboject
    3.         Ray raytall = new Ray(rays1.transform.position,rays1.forward);
    4.         Debug.DrawRay(rays1.transform.position, rays1.forward * 10,Color.cyan);
    5.         if (Physics.Raycast(raytall,out hit2,10)) {
    6.            
    7.             if (hit2.collider.CompareTag("enemy")) {
    8.                 ray1_bool = true;
    9.             }
    10.             else {
    11.                      // not work
    12.                 ray1_bool = false;
    13.                   }
    14.  
    15.             }
     
  2. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    Mentally run through what happens in that code when the ray hits nothing. Does line 12 ever get hit?

    At line 5, if the ray hits nothing then the whole block from lines 6 to 15 is skipped. That means that the tag comparison on line 7 never gets run, so it doesn't fail, and its "else" block is irrelevant.

    Probably you need to make your else block come from the line 5 branch rather than the line 7 branch.
     
  3. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    Maybe you right. but what i did to solve this issue, i remove the 12 line to above first line and worked :cool:
    Thank you
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    Yes, that will also work, because you're now resetting it to "false" before every check. It's a reasonable enough approach. However, you really ought to spend the time to understand how your code works - there should be no "maybe" about why it didn't work before or, more importantly, why it does work now.
     
    Quast and Munchy2007 like this.