Unity C#yield返回新的WaitForSeconds正在停止协同程序

时间:2016-03-02 19:10:34

标签: c# unity3d unity5

我想使用一个协程让玩家在拍摄新子弹之前稍微等一下,但它永远不会超过收益率。这是代码

 protected override void Start () {
     base.Start ();
     animator = GetComponent<Animator> ();
     score = GameManager.instance.playerScore;
     playerLives = GameManager.instance.playerLife;
 }
 void Update(){
     int horizontal = (int)Input.GetAxisRaw("Horizontal");
     AttemptMove (horizontal, 0);
     if (Input.GetKeyDown ("space")) {
         if(canShoot){
         Vector3 shootPosition = transform.position + new Vector3 (0, 0.5f, 0);
         Instantiate (bullet, shootPosition, Quaternion.identity);
         StartCoroutine(Shoot());
         }
     }
 }

 IEnumerator Shoot(){
     Debug.Log("Start");
     canShoot=false;
     yield return new WaitForSeconds (shootingTimeDelay);
     canShoot=true;
     Debug.Log("End");
 }

shootingTimeDelay设置为1.1f。我没有在任何地方销毁我的gameObject,它在我项目的其他脚本中正常工作。

它从不打印End。我不知道出了什么问题

2 个答案:

答案 0 :(得分:2)

我会说不要在这样的事情上使用协程。

尝试这样做,看看你是否得到更好的恢复

private float time = 0;

public float fireTime = 1.1f;

private void Update()
{
  time += Time.deltaTime;

  if(Input.GetKeyDown("space") && time >= fireTime)
  {
    Vector3 shootPosition = transform.position + new Vector3 (0, 0.5f, 0);
    Instantiate (bullet, shootPosition, Quaternion.identity);
    time = 0;
  }
}

答案 1 :(得分:0)

好的,我发现了这个错误。我在它的超类中有一个叫做StopAllCoroutines的方法但是由于某种原因我直到现在都没有想过它。将其更改为StopCoroutine(&#34;我的协程名称&#34;)现在它完美无缺:)

相关问题