Unity C# yield return new WaitForSeconds 正在停止协程
Unity C# yield return new WaitForSeconds is stopping coroutine
我想使用协程让玩家在发射新子弹之前稍等片刻,但它永远不会超过 yield。这是代码
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。我没有在任何地方破坏我的游戏对象,它在我项目的其他脚本中正常工作。
它从不打印 End。我不明白哪里出了问题
我会说不要为这样的事情使用协程。
尝试这样做,看看你是否得到更好的结果
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;
}
}
好的,我找到了错误。我在其超类中有一个名为 StopAllCoroutines 的方法,但出于某种原因我直到现在才开始使用它。将其更改为 StopCoroutine("name of my coroutine") 现在它可以完美运行 :)
我想使用协程让玩家在发射新子弹之前稍等片刻,但它永远不会超过 yield。这是代码
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。我没有在任何地方破坏我的游戏对象,它在我项目的其他脚本中正常工作。
它从不打印 End。我不明白哪里出了问题
我会说不要为这样的事情使用协程。
尝试这样做,看看你是否得到更好的结果
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;
}
}
好的,我找到了错误。我在其超类中有一个名为 StopAllCoroutines 的方法,但出于某种原因我直到现在才开始使用它。将其更改为 StopCoroutine("name of my coroutine") 现在它可以完美运行 :)