Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Gun doesn't damage enemies until I do this

Discussion in 'Scripting' started by KaiXGT, Mar 1, 2021.

  1. KaiXGT

    KaiXGT

    Joined:
    Feb 12, 2021
    Posts:
    13
    Soooo I have a controller script for a Deagle I am making. When I shoot the enemy, it doesn't damage them at all but I noticed when I pause the game, hover my mouse over the editor, click, go back to the game and resume, it then damages the enemies.

    Note: I have another gun, the P90, which uses the exact same method for damaging an enemy, and it works perfectly fine
    Note 2: There are no compiler errors
    Note 3: I am yet to test this out on an actual build

    Code (CSharp):
    1.     void RayCastForEnemy()
    2.     {
    3.         RaycastHit hit;
    4.         if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, 1 << LayerMask.NameToLayer("Enemy")))
    5.         {
    6.             Target target = hit.transform.GetComponent<Target>();
    7.             if (target != null)
    8.             {
    9.                 target.TakeDamage(damage);
    10.                 Debug.Log("Hit an enemy with the Handcannon");
    11.             }
    12.         }
    13.     }
    Please help, and thank you
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    I don't really know the explanation for the behavior you're seeing, but you should follow all the normal debugging steps.

    First: add more log statements to shed more light on where things are going wrong.

    The other thing I would check specifically in this case, is are you passing the correct parameters into Raycast? I'm pretty sure your 4th parameter which you seem to intend to be a layer mask is actually a max distance parameter. I tested with the same argument types have and saw this:
    upload_2021-3-1_19-46-25.png
    Therefore you probably are not using any layer mask at all, and in fact the player is hitting itself with its raycast or something.
     
    KaiXGT likes this.
  3. KaiXGT

    KaiXGT

    Joined:
    Feb 12, 2021
    Posts:
    13
    Thanks for the reply

    I think I have it working now, thank you for the input
    Also, I think the layerMask is a parameter because it says in the docs and it doesn't give me any errors but whatever lol

    again, tyty
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    LayerMask is a parameter but it's the 5th parameter for that particular overload of the method. You're simply passing in a max distance in a really weird way.
     
    KaiXGT likes this.
  5. KaiXGT

    KaiXGT

    Joined:
    Feb 12, 2021
    Posts:
    13
    Ohhh okay I get it now. Thank you again