# Raycast collision not working

I've tried to do a gun mechanic for my 3d game but when I tried to write ray cast it didn't work only layer that is printed is 0 even though it shoots and gets stopped by an obstacle here's the important code

private void Update()
{
if (!Input.GetButton("Fire1") || !(Time.time > nextFire))
{
return;
}
nextFire = Time.time + fireRate;
Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.5f));
laserLine.SetPosition(0, gunEnd.position);
if (Physics.Raycast(rayOrigin, fpsCam.transform.forward, out var hit, weaponRange))
{
print(hit.collider.gameObject.layer);
if (hit.collider.gameObject.layer == enemyLayer)
{
laserLine.SetPosition(1, hit.point);
//decrease enemy health
}
else
{
laserLine.SetPosition(1, rayOrigin + fpsCam.transform.forward * weaponRange);
}
}
}


all of the variables are serialaized on inspector window and no mistakes were made . i even checked if the enemy did have a working collider which it did and the layer output was 3(enemy)

I would use tags instead of layers. If you are looking to detect enemy hit collision with raycast, layers are generally not the best method.

Call FireWeapon() whenever you want to fire a Raycast. Create a new tag in the unity editor called "Enemy". Whenever the ray hits a collider with the tag assigned Enemy, you should be able to handle whatever commands needed. Realistically, you can just use my raycast if check in your current function if everything is working as it should. The ray will be forward out from the cameras front direction.

Please let me know if I can be of any further help

void FireWeapon() {
//Created a camera type with name PlayerCamera
float weaponRange = 150f;
if (Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out RaycastHit hit, weaponRange)) {
if (hit.collider.CompareTag("Enemy")) {
// Decrease health
}
}

• well by messing up by the code and using tags i've figured out that from the beginning it was hitting the player because i made it so big thank you so much :D it took so long to figure out Jun 5 at 21:53