Home > OS >  Unity, Multiple Booleans to make another True
Unity, Multiple Booleans to make another True

Time:05-25

So first off, I'm terrible at coding but what I'm doing is trying to make a scene if you hit 4 buttons a 5th will appear. I'm just trying to have 4 variables true to make the 5th true. Any advice?

private void Update()
{
     if ((T1 ,T2, T3 ,T4 ) = true)
    {
        Button1 = true;
        Debug.Log("FINALLY");
    }
   
}

void OnTriggerEnter(Collider other)
{
    if (other.tag == "T1")
    {
        T1 = true;
        Debug.Log("T1");
    }

    if (other.tag == "T2")
    {
        T2 = true;
        Debug.Log("T2");
    }

     if (other.tag == "T3")
    {
        T3 = true;
        Debug.Log("T3");
    }

    if (other.tag == "T4")
    {
        T4 = true;
        Debug.Log("T4");
    }
  
   
}

}

CodePudding user response:

This should work.

private void Update()
{
    if (T1 && T2 && T3 && T4)
    {
        Button1 = true;
        Debug.Log("Button1 became true");
    }  
}

void OnTriggerEnter(Collider other)
{
    if (other.tag == "T1")
    {
        T1 = true;
        Debug.Log("T1 became true");
        Update();
    }

    else if (other.tag == "T2")
    {
        T2 = true;
        Debug.Log("T2 became true");
        Update();
    }

    else if (other.tag == "T3")
    {
        T3 = true;
        Debug.Log("T3 became true");
        Update();
    }

    else if (other.tag == "T4")
    {
        T4 = true;
        Debug.Log("T4 became true");
        Update();
    }
}

CodePudding user response:

You could have your 5 buttons under one game object in the scene. Then, create and attach this script to the parent game object.

public class ButtonControl : MonoBehaviour
{
    public GameObject extraButton;
    public int neededButtons = 4;
    private List<Button> buttonList = new List<Button>();

    public void OnButtonPress(Button button)
    {
        if(buttonList.Contains(button) == false)
        {
             buttonList.Add(button);
             Debug.Log(button.name   " became true");
             if(buttonList.Count == neededButtons)
             {
                  extraButton.SetActive(true);
                  Debug.Log("FINALLY");
             }
        }
    }
}

Then for each of the 4 acting buttons, you drag the object to the button listener, then drag the Button component to the parameter of the listener. Fifth is set off.

Any tap on the buttons will try to add them to the list, first making sure they are not already there (you could use HashSet if you are familiar with this data container). Then, for any press, if the collection has 4 items, then show the button.

As a result, no need for update, no need for extra boolean and extra tag for each button. You can also extend to as many buttons as you need while reusing the same script.

If you are not using the UI system, you can use the same logic with whatever is detecting the button press.

  • Related