【问题标题】:my While loop executes everything at once ( C#)我的 While 循环一次执行所有内容(C#)
【发布时间】:2014-10-16 08:21:04
【问题描述】:

所以我将这个脚本附加到游戏中,并且我添加的 While 循环应该跟踪弹药并在每次我发射火箭时下降 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;         
    } 
  }
}

谢谢!

【问题讨论】:

  • 您的标题无法解释您的问题。 Write a better one 代替。
  • 嗯...是的! while 循环基本上立即运行完成......
  • 在while循环中设置断点并开始调试。当程序在循环内停止时,条件至少符合一次。如果这不是您的问题,请说明问题。
  • 如果你只想每次点击发射一枚火箭,你应该使用if而不是while
  • 我先有一个“if”,但任务是使用 while 循环。

标签: c# loops while-loop


【解决方案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;
} 

我猜你需要将 while 更改为 if 以检查是否有任何火箭要发射:

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

【讨论】:

    【解决方案2】:

    您误解了while 循环是什么。关键是loop这个词。循环体可能会被执行多次:

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

    循环的条件决定是否执行主体。当循环体完成时,再次测试条件。如果条件评估为真,则主体再次执行。这种循环一直持续到条件评估为假为止。

    我猜你打算用if 声明来写这篇文章。

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

    在这里,主体最多执行一次。如果条件评估为真,则执行 if 语句的主体。没有循环,没有迭代。

    【讨论】:

      【解决方案3】:

      删除循环!毕竟,您希望每次发射火箭时只发射一个单位的弹药。

      【讨论】:

        【解决方案4】:

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

        你想要的只是在void FireRocket() 里面有if,来检查Ammo 是否可以射击......像这样

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

        void FireRocket()里面

        Ammo 结束时,else 将拥有您想要显示给玩家的内容..

        【讨论】:

          猜你喜欢
          • 2015-06-19
          • 2013-08-12
          • 1970-01-01
          • 1970-01-01
          • 2016-01-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多