Home > database >  First click of Unity UI Button does not respond
First click of Unity UI Button does not respond

Time:12-03

I'm trying to use Unity's UI system .

What I want is that I have a button #1 as a card image and I have button 2 as a spade image. First I will click spade image and it's indicator will turn on. After that I will click the card image to make the Spade Icon image disappear. I managed to get variables from script to another script but whatever I do the first click of the Spade Button, the indicator lights up and spadeselected bool changes in the inspector. While spadeselected is true, the first click of the Card image doesn't do a thing. After clicking twice and so on everything works fine. What could cause this problem?

My main script for card button:

public class main : MonoBehaviour
{
    private bool ace = false;
    
    spadestatement _spadestatement;
    public GameObject spadebutton;
        
    public GameObject spade_icon;

    private void Awake()
    { 
        _spadestatement = spadebutton.GetComponent<spadestatement>();
    }

    private void Start()
    {
        gameObject.GetComponent<Button>().onClick.AddListener(turnoff);
    }

    private void turnoff()
    {
        ace ^= true;
        
        if (_spadestatement.spadeselected == true)
        {   
            spade_icon.SetActive(ace);
        }
    }
}

My spadestatement script for spade button:

public class spadestatement : MonoBehaviour
{
    public bool spadeselected;
    public GameObject indicator;

    void Start()
    {
        gameObject.GetComponent<Button>().onClick.AddListener(select);
    }

    public void select()
    {
        spadeselected ^= true;
        indicator.SetActive(spadeselected);
    }
}

And here is a picture to make it more understandable: enter image description here

CodePudding user response:

When spadeselected is true, the first time you call turnoff() :

private void turnoff()
{
    ace ^= true; //first time : after the assignment, ace is true
    
    if (_spadestatement.spadeselected == true)
    {   
        spade_icon.SetActive(ace); // since ace is true, set spade_icon active
    }
}

The second time you call turnoff(), ace become false, thus spade_icon is deactive.

If you want to turn on/off the spade_icon, maybe try this one:

private void turnoff()
{
    ace ^= true; //first time : after the assignment, ace is true
    
    if (_spadestatement.spadeselected == true)
    {   
        spade_icon.SetActive(!ace); // since ace is true, set spade_icon deactive
    }
}

Or, if you don't want to bind the active/deactive behaviour of spade_icon with ace, you can:

private void turnoff()
{
    if (_spadestatement.spadeselected == true)
    {   
        spade_icon.SetActive(!spade_icon.activeSelf);
    }
}
  • Related