Why Does the Ray change my object position?

Hello. I am following the laser beam tutorial in the videos of the Learn section.

However, when I try to implement the lasers something strange happens, when I shoot my lasers
the gun tip changes its position, the laser appears in the new position and slowly moves away. I tried to keep in the position I am setting it to, but it keeps changing its position and then moving away.

Here is the code I am using. I will be thankful for any kind of help.

using UnityEngine;
using System.Collections;

public class OverWeapon : MonoBehaviour
{
    LineRenderer line;
    //public Transform rifleGun;
    void Start()
    {

        line = gameObject.GetComponent<LineRenderer>();
        line.enabled = false;
    }

    void Update()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
        Debug.DrawRay(transform.position, -forward, Color.green);
        if(Input.GetKeyDown(KeyCode.Space))
        {
            StopCoroutine("shootBeam");
            StartCoroutine("shootBeam");
        }
    }

    IEnumerator shootBeam()
    {
        line.enabled = true;

        while(Input.GetKey(KeyCode.Space))
        {
            //Ray ray = new Ray(transform.position, transform.forward);//I HAVE DISCOVERED THAT THIS IS SOMEHOW CAUSING THE PROBLEM
            line.SetPosition(0,ray.origin);
            line.SetPosition(1,ray.GetPoint(100));
            yield return null;
        }

        line.enabled = false;
    }

}

I’m not sure if this is the problem, but you shouldn’t use a while loop that way.

And your code has a lot of redundancy in it.
Try this:

Update() {
line.enabled = Input.GetKey (KeyCode.Space) );
if (line.enabled) {
line.SetPosition (0, transform.position);
line.SetPosition (1, transform.TransformPoint (Vector3(0,0,100)));
}