我的While循环一次执行所有内容(C#)

时间:2014-10-16 08:21:04

标签: c# loops while-loop

所以我把这个脚本附加到一个游戏中,我添加的While循环应该跟踪Ammo并且每次我射击火箭时都会下降1,但是当我在游戏中离开点击时(射击)它会射击我所有的弹药一旦。我的代码:

public class CreateRocket : MonoBehaviour {
public Rigidbody rocket;
public float speed = 10f;
public int aantalRaketten;
public int Ammo = 10;

// Use this for initialization
void Start () {}

// Update is called once per frame
void Update () {
    if (Input.GetButtonDown("Fire1"))
    {
      FireRocket();
    }
}

void FireRocket()
{      
    while (Ammo >= aantalRaketten) 
    {
      Ammo--;
      Rigidbody rocketClone = (Rigidbody)Instantiate(rocket, transform.position + transform.forward * 2, transform.rotation);
      rocketClone.velocity = transform.forward * speed;         
    } 
  }
}

谢谢!

4 个答案:

答案 0 :(得分:1)

嗯:但是当我在游戏中点击(拍摄)时,它会立即拍摄我的所有弹药

是的,这正是你在while循环中所做的,运行直到你的条件为假(aantalRaketten = 0?):

while (Ammo >= aantalRaketten) 
{
  Ammo--;
  Rigidbody rocketClone = (Rigidbody)Instantiate(rocket, transform.position + transform.forward * 2, transform.rotation);
  rocketClone.velocity = transform.forward * speed;
} 

我猜你需要将时间更改为if以检查是否有任何火箭可以射击:

if (Ammo > 0) 
{
  Ammo--;
  Rigidbody rocketClone = (Rigidbody)Instantiate(rocket, transform.position + transform.forward * 2, transform.rotation);
  rocketClone.velocity = transform.forward * speed;
} 

答案 1 :(得分:1)

你误解了while循环是什么。关键是循环这个词。循环体可以多次执行:

while (Ammo >= aantalRaketten) 
{
    Ammo--;
    ....
} 

循环的条件决定了主体是否被执行。当循环体完成时,再次测试条件。如果条件评估为真,则身体再次执行。此循环继续,直到条件评估为false。

我认为你打算用if语句来写这个。

if (Ammo >= aantalRaketten) 
{
    Ammo--;
    ....
} 

这里,身体最多执行一次。如果条件计算为true,则执行if语句的主体。没有循环,没有迭代。

答案 2 :(得分:0)

删除循环!毕竟你想要每次发射火箭时只派遣一个弹药单位。

答案 3 :(得分:0)

当你调用void FireRocket()一次时,它进入并完全运行while()循环并发射所有火箭..

你想要的只是在if内只有void FireRocket(),以检查Ammo是否还有拍摄......就像这样

if(Ammo >= aantalRaketten)
{
    Ammo--;
    Rigidbody rocketClone = (Rigidbody)Instantiate(rocket, transform.position +  transform.forward * 2, transform.rotation);
    rocketClone.velocity = transform.forward * speed;
}

void FireRocket()

else结束时,Ammo会显示您想要播放的内容。