2016-03-02 77 views
0

我想用一个协程来让玩家在拍摄新子弹之前等一会儿,但它永远不会超过收益率。代码如下Unity C#收益率返回新WaitForSeconds正在停止协程

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,并且它可以在我的项目中的其他脚本中正常工作。

它从不打印结束。我没有得到什么错

+0

'Time.timeScale'大于'0'? –

+0

它等于1 –

+1

这是c#上帝告诉你不使用协程 – MickyD

回答

2

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

试图这样做的,看看你得到更好的restults

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; 
    } 
} 
+0

这是更好的解决方案,然后使用协程,但我们仍然应该在OP代码中找到问题。 –

+0

该解决方案的工作原理非常完美。我在接受它之前等待,因为我想知道我的代码中的问题 –

+1

代码中必须有一个外部因素。我用你的协同程序做了一个测试,它工作得很好。我会看看脚本执行顺序或任何其他可能远程涉及的类 –

0

好吧,我发现的bug。我在它的超类中有一个名为StopAllCoroutine的方法,但由于某种原因,我从来没有尝试过它。更改为StopCoroutine(“我的协同程序的名称”),现在它完美:)