Gun doesn't damage enemies until I do this

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

    void RayCastForEnemy()
    {
        RaycastHit hit;
        if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, 1 << LayerMask.NameToLayer("Enemy")))
        {
            Target target = hit.transform.GetComponent<Target>();
            if (target != null)
            {
                target.TakeDamage(damage);
                Debug.Log("Hit an enemy with the Handcannon");
            }
        }
    }

Please help, and thank you

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:


Therefore you probably are not using any layer mask at all, and in fact the player is hitting itself with its raycast or something.

1 Like

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

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.

1 Like

Ohhh okay I get it now. Thank you again