I added a laser weapon to my spaceship, so far so good It’s a coroutine that engages when you press input fire1 It uses line renderer and rays to drawn the line a detect hits, however I want the beam to switch on and off rapidly while the player holds down the fire1 button and I can’t for the life of me work out how to do this.
This is what I have written but it doesn’t work, the beam never starts and it goes into cooldown right away.
`void Update ()
{
if (Input.GetButtonDown ("Fire1") )
{
StopCoroutine("FireLaser");
StartCoroutine("FireLaser");
}
}
IEnumerator FireLaser()
{
Debug.Log ("coroutine started");
line.enabled = true;
LaserLight.enabled = true;
LaserAudio.Play();
while(Input.GetButton("Fire1"))
{
line.renderer.material.mainTextureOffset = new Vector2(0, Time.time);
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
line.SetPosition(0, ray.origin);
line.SetPosition(1, ray.GetPoint (1000));
if(Physics.Raycast(ray, out hit, 1000))
{
line.SetPosition(1, hit.point);
if(hit.rigidbody)
{
if (hit.transform.gameObject.tag == "Enemy")
{
hit.transform.SendMessage("ApplyDamage", 100, SendMessageOptions.DontRequireReceiver);
}
}
}
float delay = 1f;
while (delay > 0) // while cooldown time running...
{
Debug.Log("Entered cooldown");
// update beam endpoints
line.SetPosition(0, transform.position);
line.SetPosition(1, transform.position);
// decrement delay time:
delay -= Time.deltaTime;
// let Unity free until next frame:
yield return null;
}
line.enabled = false;
LaserLight.enabled = false;
LaserAudio.Stop();
yield return null;
}
}`