Strange issue with function on ui button.

Hey,

While porting a game to mobile I’ve ran into a problem with executing code on a UI button. I have the following jump code:

            if (Input.GetButton("Jump") && !_rolling)
            {
                Jump();
            }
    public void Jump()
    {


        if (_jumping == false)
        {
            Debug.Log("jumped");
            _jumping = true;
            _moveDirection.y = _jumpSpeed;
           _anim.SetBool("Jump", _jumping);


        }
        if (_onLedge)
        {
            _anim.SetTrigger("ClimbUp");

        }
    }

This code works completely fine when the space key is pressed. The problem is making a ui button that executes the Jump() function.

When I do this, the console does log the “jumped” indicator that the code is being ran but the jump doesn’t actually occur. If the player _onledge is true it also climbs up correctly so the code is being ran but isnt behaving the same as when the space key is pressed, which seems odd because its the same function.

Does anyone have any ideas to maybe why this isn’t working?

Thanks

probably related to where within your Update() method your first snippet is being called, and how /when some of those variable reset/get set to something else. For example you might be overwriting _moveDirection elsewhere in Update.

Break it apart so that the following happens sequentially for each piece of input.

For instance, for the Jump(), make an intent boolean:

Each frame:

  • presume no input (clear intent boolean)
  • read keys, set intent
  • read buttons, set intent
  • read anything else (Kinect? Accelerometer? etc.), set intent

Only once you have ALL the possible ways of input should you consider processing whether there is a Jump() intent and consider if it is reasonable to jump at that point.

Hey,

Thank you both!

I looked a little further into bits that were potentially altering _moveDirection and found the following line in the Update function

            _moveDirection.y -= _gravity * Time.deltaTime;

I’m not entirely sure why this was conflicting with the UI button jump and not the space bar jump but putting it inside a statement to only apply gravity when not grounded has fixed the problem.