Search Unity

Active bool to true by Button

Discussion in 'Scripting' started by ContraXGaming, Feb 17, 2019.

  1. ContraXGaming

    ContraXGaming

    Joined:
    Dec 15, 2017
    Posts:
    78
    Hello. I'm trying to active bool by clicking the mobile UI button.

    I've already tryed this:

    Code (CSharp):
    1. public class Buttons : MonoBehaviour {
    2.     public bool xAttack;
    3.  
    4.     public void xAttackBool()
    5.     {
    6.         xAttack = true;
    7.     }
    8. }
    and then i've added xAttackBool() method to onclick event.

    But, even when i do that it wont work (like it sometimes turns a bool to true, sometimes not).

    Can someone help me? Thanks
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Where do you set the bool back to false?
     
  3. ContraXGaming

    ContraXGaming

    Joined:
    Dec 15, 2017
    Posts:
    78
    In code, just not shown:
    Code (CSharp):
    1. [SerializeField] private float _duration = 1f;
    2.     private float _timer = 0f;
    3.  
    4. _timer += Time.deltaTime;
    5. if (_timer >= _duration && xAttack == true) {
    6.                 _timer = 0f;
    7.                 xAttack = false;
    8.             }
    It goes to false after 1 sec if its true, and it's working. But the issue is in button, when i press it
    sometimes it turns bool to true sometimes not
     
    Last edited: Feb 17, 2019
  4. zioth

    zioth

    Joined:
    Jan 9, 2019
    Posts:
    111
    You might need to set _timer=0f in xAttackBool(). If you click the button close to the end of the timer, xAttack will turn on, and immediately off again.
     
    ContraXGaming likes this.
  5. ContraXGaming

    ContraXGaming

    Joined:
    Dec 15, 2017
    Posts:
    78
    Tryed it, but it still wont work...
     
  6. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Your issue is here. As _timer is always being added too it is already greater than _duration when xAttack is set to true. The problem isn't with the button, it is with your code to disable the bool.
     
  7. ContraXGaming

    ContraXGaming

    Joined:
    Dec 15, 2017
    Posts:
    78
    Sorry, but won't work... tryed it like this:
    Code (CSharp):
    1. public void xAttackBool(){
    2.         jay.xAttack = !jay.xAttack;
    3.     }
    and deleted this code:
    Code (CSharp):
    1.             _timer += Time.deltaTime;
    2. if (_timer >= _duration && xAttack == true) {
    3.                 _timer = 0f;
    4.                 xAttack = false;
    5.             }
    still doesn't work...
    Maybe depends on the version of a unity I'am using...
     
    Last edited: Feb 17, 2019
  8. ContraXGaming

    ContraXGaming

    Joined:
    Dec 15, 2017
    Posts:
    78
    thank you very much guys the issue is solved.

    zioth' s right i've just needed to add timer = 0f in AttackBool().
     
    Last edited: Feb 19, 2019