Search Unity

New UI Button having trouble with If statements?

Discussion in 'Scripting' started by CodexMaster, Aug 29, 2014.

  1. CodexMaster

    CodexMaster

    Joined:
    Aug 29, 2014
    Posts:
    2
    Hey everyone,

    I have been playing around with unity 4.6 beta and was wondering if anyone has had similar problems. I have attempted to create a UI button which runs a function when it is clicked. It all works up until I add IF statements into the equation. The button is registering the click but not running either of the if statements. Is this a bug to do with the new UI or something I have done wrong?

    Note: This is using the On Click () part of the New UI Button Script to run OpenTab ()

    var tab : GameObject;
    var touch : int = 0;

    function Start (){
    touch = 0;
    }

    function OpenTab () {
    if (touch == 0){
    tab.transform.Translate(-268,0,0);
    touch = 1;
    Debug.Log ("touched");
    }
    if (touch == 1){
    tab.transform.Translate(268,0,0);
    touch = 0;
    }
    Debug.Log ("touched");
    }
     
  2. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    No bug, just a logical misstep. Both if statements are being entered, as you set the conditions for the second block within the first. Since your second statement negates the first, it looks like nothing is happening. Make the second block an else if statement. or just else.

    For better debugging, make your Debug statements different so you can see which ones are being called

    Lastly, use bools for a toggle variable like touch, which only has 2 states that represent true/false.
     
    CodexMaster likes this.
  3. CodexMaster

    CodexMaster

    Joined:
    Aug 29, 2014
    Posts:
    2
    Thank you, works perfectly now.