Home > Software engineering >  Why Is The "while" Function For C# Crashing Game Engine?
Why Is The "while" Function For C# Crashing Game Engine?

Time:10-21

I am working on a game made in Unity Engine. For Movement, I have used vector2. But for vector2, you need to spam the buttons in order for the player to move. So i tried "while" function to loop the process. Here is the main code

    if (Input.GetKeyDown(KeyCode.W))
    {
        i = 5;

    }

    //test

    if (Input.GetKeyUp(KeyCode.W))
    {
        i = 1;
    }

    
   

    while(i !=1)
    {
        rb.AddForce(Vector2.up * JumpForce);
    }

However, when I run it the engine crashes. Why? Just to let you know, there are no compiler errors.

CodePudding user response:

In Unity, the physics movement should be done in FixedUpdate, and input checking in Update. Something like this:

[SerializeField] private Rigidbody _rb;
[SerializeField] private float _jumpForce;

private bool _addForce;

private void OnUpdate()
{
    _addForce = Input.GetKey(KeyCode.W);
}

private void FixedUpdate()
{
    if (_addForce) _rb.AddForce(Vector2.up * _jumpForce);
}

If you add a while in the Update, it will stuck in that frame, freezing the main loop, and the engine can't poll for new inputs, so your Update can't continue.

CodePudding user response:

The repeated addforces might be a bit much for the PC.

Do this:

if (Input.GetKey(KeyCode.W))
{
    rb.AddForce(Vector2.up * JumpForce);
}

This way it only moves when key is being held.

  • Related