Search Unity

How to force release a button through code?

Discussion in 'Scripting' started by cuber01, Aug 20, 2019.

  1. cuber01

    cuber01

    Joined:
    Sep 16, 2016
    Posts:
    21
    Right now what I have set up is an event trigger on a UI Button that when the user presses and holds down the button it will hold the character in place and when the user lets go of the button the character is able to move again. What I am trying to do is have it so after a certain amount of time has passed of the user holding down the button the character will just start moving. No matter how long the user holds down the button the character will start moving after a certain amount of time has passed. Here is the code that I have right now. All that happens right now is when the user holds down the button the character stops moving but if the user keeps holding down the button the character will not move. I am unable to get it so that the character will start moving after a certain amount of time.


    if (_sliding && timer >= 0.2)
    {
    rb.constraints = RigidbodyConstraints.FreezePositionY;
    }
    else if (!_sliding)
    {
    rb.constraints &= ~RigidbodyConstraints.FreezePositionY;
    rb.constraints = RigidbodyConstraints.FreezePositionX;
    }


    The timer I have running in a different part of the code. The timer only runs when the user presses and holds down the button.

    If anybody has any suggestions that would be great!

    Thanks
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    No idea what "_sliding" is for. If you don't want to post the entire script, you should explain what you are posting. But I'm going to venture a guess that you reset the timer every time the button gets pressed, and somehow _sliding stays true so long as the button is held down. Something like this might work then.

    Code (csharp):
    1. if (_sliding && timer >= 0.2 && timer <= 3f)
    2. {
    3.     rb.constraints = RigidbodyConstraints.FreezePositionY;
    4. }
    5. else if (_sliding && timer > 3f)
    6. {
    7.     rb.constraints = RigidbodyConstraints.None;
    8. }
    9. else if (!_sliding)
    10. {
    11.     rb.constraints &= ~RigidbodyConstraints.FreezePositionY;
    12.     rb.constraints = RigidbodyConstraints.FreezePositionX;
    13. }
     
  3. cuber01

    cuber01

    Joined:
    Sep 16, 2016
    Posts:
    21

    Thanks so much! What was suggested did work!
     
    Joe-Censored likes this.