- Home /
This post has been wikified, any user with enough reputation can edit it.
stopping a Coroutine while it is running.
I have a script for a laser. The script runs great and there is no problems with it. What I want to happen is that after the player has hit fire1 the laser fires for a few seconds and then stops. However I am not able to figure out how to get it to do that. As of right now it fires until you release fire1. Any ideas on how to do that? Here is the script as it is currently written. I need this for a college class and I have not been able to find any answers on it so far. using UnityEngine; using System.Collections;
public class LaserDesign : MonoBehaviour
{
LineRenderer line;
void Start ()
{
line = gameObject.GetComponent<LineRenderer>();
line.enabled = false;
}
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
StopCoroutine("FireLaser");
StartCoroutine("FireLaser", 2.0F);
}
}
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, 1000))
{
line.SetPosition(1, hit.point);
if(hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition(transform.forward * 50, hit.point);
}
}
else
line.SetPosition(1, ray.GetPoint(1000));
yield return null;
}
line.enabled = false;
}
}
Comment
Best Answer
Answer by whydoidoit · Mar 03, 2014 at 08:47 AM
Simply terminate you enumerator after two seconds or when the button is released like this:
using UnityEngine;
using System.Collections;
public class LaserDesign : MonoBehaviour
{
LineRenderer line;
void Start ()
{
line = gameObject.GetComponent<LineRenderer>();
line.enabled = false;
}
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
StopCoroutine("FireLaser");
StartCoroutine("FireLaser", 2.0F);
}
}
IEnumerator FireLaser(float lengthOfTime)
{
line.enabled = true;
var t = Time.time;
while(Input.GetButton("Fire1") && Time.time - t < lengthOfTime)
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
line.SetPosition(0, ray.origin);
if(Physics.Raycast(ray, out hit, 1000))
{
line.SetPosition(1, hit.point);
if(hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition(transform.forward * 50, hit.point);
}
}
else
line.SetPosition(1, ray.GetPoint(1000));
yield return null;
}
line.enabled = false;
}
}