Rapid Laser?

I’m trying to make my lasers shoot rapidly instead of shooting a long line
here is my code, thanks!

using UnityEngine;
using System.Collections;

public class LaserScript : MonoBehaviour 
{
	LineRenderer line;
	
	void Start () 
	{
		line = gameObject.GetComponent<LineRenderer>();
		line.enabled = false;
	}
	void Update () 
	{
		if(Input.GetButtonDown("Fire1"))
		{
			StopCoroutine("FireLaser");
			StartCoroutine("FireLaser");
		}
	}
	IEnumerator FireLaser()
	{
		line.enabled = true;
		
		while(Input.GetButton("Fire1"))
		{
			Ray ray = new Ray(transform.position, transform.forward);
			RaycastHit hit;
			
			line.SetPosition(0, ray.origin);
			
			if(Physics.Raycast(ray, out hit, 100))
			{
				line.SetPosition(1, hit.point);
				if(hit.rigidbody)
				{
					hit.rigidbody.AddForceAtPosition(transform.forward* 10, hit.point);  

				}
			}
			else
				line.SetPosition(1, ray.GetPoint(100));
			
			yield return null;
		}
		
		line.enabled = false;
	}
}

Note: this is a simple solution, there is enough place for improvements

Step 1: Create A Laser Object

Make a new Object

  • add a Line Renderer.
    • Cast Shadow false
    • receive shadow false
    • Use World Space false
    • Start Widt = End Width = 0.03.
    • Positions > Element 1 > Z = 0.3
  • add a new Script Laserbeam

Save it as Prefab.

Step 2: Laserbeam Script

Has two public Vector3 attributes “From” and “To”, and an private float attribute “time”.

using Vector3.Lerp to move the laser beam from “From” to “To” in 1/3 second (maybe faster)
if reached the position (distance between transform.position and “To” smaller than an epsilon) destroy this.gameObject

Step 3: Throw away your script

Your Script will be fairly simple: if the left mouse button is pressed (you can do that with “Fire1” like you’ve done) you do two things:

  1. sending an raycast to determine what you’ll hit (the laserbeam should be so fast, that the time it takes to travel should not make a difference on what to be hit - as i said: here’s place for improvements)
  2. create an instance of your prefab, setting “From” to your raycast start point, setting “To” to your raycast hit point (if nothing hit your “To” calculate a point based on your raycast direction)

you may want a time variable to implement something like a cooldown, maybe some precision variable, recoil and so on and so on.