Raycast pointer flinch

I’m new to Raycast and I started off basic with the following below. From what I see in tutorials, it should work and follow where my gun is pointing, which it does to an extent. I tested it out by rotating my gun around while firing, and the pointer shoots out of the gun barrel most of the time. There are a few angles where I would fire, and the pointer will flinch 90 degrees and point the wrong way. Can anyone please help me out?

UPDATE: When I fire my weapon, the enemy health would sometimes go down even when I’m pointing it away from the enemy. Sometimes it works and doesn’t apply damage when not pointing at the enemy, sometimes it applies damage even when weapon is facing away.

RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hit, 500))
{
     // Interact with objects
}
Debug.DrawRay(ray.origin, hit.point - ray.origin, Color.red);

is the gun… or whatever object that the raycasting script is applied to…
is it parented to an object, and its getting the parent rotation and not the guns? … lol i had this problem…

uh, some rotation script i had with quaternions would be backwards when you pass 180 degrees…
(cant remember exactly … quaternion.lookat ??? )

are you certain “forward” is the correct axis? (positive Z )

just some thoughts…

@ CaoMengde777

I have this within another if statement I have, which states that if I left click, it will fire the raycast. I just added a few more lines of code last night, so here’s the updated version:

RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hit, 500))
{
     foe = GameObject.FindWithTag("Enemy");
     bullet = GameObject.FindWithTag("Bullet");

     foeCombat.EnemyDamaged(1); // Enemy being damaged is true
}
Debug.DrawRay(ray.origin, hit.point - ray.origin, Color.red);

I have this attached to barrel_gun, which is a child of the weapon, and the weapon is a child of the player game object (parent). The barrel_gun would fire the raycast when left click is in use. I also checked in the scene and the barrel_gun’s ‘forward’ is pointing in the positive Z axis.