I'm a coding noob. For the life of me I'm not able to figure out why the while loop is going infinitely? Any and all help is appreciated. Here is the code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LaserScript : MonoBehaviour {

LineRenderer laser;
int count;
//Vector3[] laserPoints = new Vector3[10];

void Start ()
{
	laser = GetComponent<LineRenderer> ();
	laser.enabled = false;
	//laserPoints [2] = new Vector3 (10,0,5);
}

void Update () {
	if (Input.GetKeyDown (KeyCode.LeftControl)) 
	{
			StopCoroutine ("Firing");
			StartCoroutine ("Firing");
		//Debug.DrawRay (transform.position, transform.forward, Color.red);
	}
}

IEnumerator Firing()
{
	laser.enabled = true;
	while (Input.GetKey(KeyCode.LeftControl))
	{
		Ray ray = new Ray (transform.position, transform.forward);
		RaycastHit hit;
		laser.positionCount = 10;
		laser.SetPosition (0, ray.origin);

		if (Physics.Raycast (ray, out hit, 100))
		{
			laser.SetPosition (1, hit.point);
			Debug.Log (hit.point);
			if (hit.collider.tag == "Mirror")
			{
				laser.SetPosition (2, hit.point + 100.0f * Vector3.Reflect (transform.forward, hit.normal));
			}
		}
		else
			laser.SetPosition (1, ray.GetPoint (100));

		if (Input.GetKeyDown (KeyCode.Space))
			break;
	}
	yield return null;
	laser.enabled = false;
}

}

The reason why you have an infinite loop is:

  • Input is only changed between frames. So as long as you don’t let the current frame finish the input state won’t change.
  • Your while loop only exits when the input state changes. Either when LeftControl is no longer held down, or when you press space.
  • However since you don’t yield inside your while loop, you are stuck in that while loop.

You have to put your yield return null; inside your while loop. That way the coroutine is interrupted at that point which let the current frame finish and let the input state update.