Search Unity

Raycast if-statement does not work

Discussion in 'Scripting' started by CarlHaeggman, Jan 13, 2021.

  1. CarlHaeggman

    CarlHaeggman

    Joined:
    Oct 15, 2018
    Posts:
    7
    I am currently fixing the last part of an enemy AI so it won't try to shoot the player through walls. I have attempted to do this by having a raycast go from the enemy to the player detecting if there is something in between but for some reason, it does not work and I really have no idea why. Anyone out there who could shed some light on this problem?


    RaycastHit hit;

    private void Update()
    {
    playerInRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
    if (Physics.Raycast(shootPos.position, (player.position - transform.position), out hit, attackRange) && hit.transform.CompareTag("Player"))
    {
    //DOES NOT REACH HERE
    Debug.Log(hit.transform.tag);
    agent.enabled = false;

    AttackPlayer();
    }
    else
    {
    if (agent.enabled == false)
    {
    agent.enabled = true;
    }
    ChasePlayer();
    }

    }
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,448
    i'd think this part fails, since it hasnt done the hit result yet? try if you put it before the debug.log line
    Code (CSharp):
    1. && hit.transform.CompareTag("Player")
     
  3. CarlHaeggman

    CarlHaeggman

    Joined:
    Oct 15, 2018
    Posts:
    7
    Already tried. There is nothing inside of the "hit" variable even after the first if statement.
     
  4. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,448
    is it hitting something thought? (try print hit.transform.name)
     
  5. CarlHaeggman

    CarlHaeggman

    Joined:
    Oct 15, 2018
    Posts:
    7
    Hmm, it does actually hit the player sometimes if you stand in certain spots but most of the time the raycast seems to hit the floor or random objects even if the player object is right in front.
     
  6. Sphinks

    Sphinks

    Joined:
    Apr 6, 2019
    Posts:
    267
    Do you get any errors ? Did you set the "RaycastHit" in the inspector or did you already check, which result your statement returns ?

    Maybe try the following, to see if you get true:

    Debug.Log(hit.transform.CompareTag("Player"));
     
  7. CarlHaeggman

    CarlHaeggman

    Joined:
    Oct 15, 2018
    Posts:
    7
    Just found the error. Was just me being stupid. There was a typo in the tag. (Plaeyr instead of Player).
     
    Sphinks likes this.