If GUI.Button in other script has been pressed, then do something...

Hi,

I have a lot of different C# Scripts with different GUI Buttons with Box & Labels.
They are showing the menu.
If I click on a Button, then that is opening a BOX & Label.
I have named the Buttons from B1-B8.
In every script the function of button is working with counter, therfore 1 = opened, 2 = closed.

How can I check If one of them has been pressed, then the actual is closing?
(If I click on all buttons, then all boxes are opening and this is wrong, because the boxes are layering each other and this is looking very nastily.)

My idea, but it isn’t working:

If (B2-B8 pressed)
{
counterB1==2;
}

This is just assumptions since u didn’t post the code:
I take it all the buttons have one and the same script?
In that case, every button has it’s own instance of the script.
to check the counter for button b3 for example you should find its GameObject and then its script instance by doing:
GameObject.Find(“buttonnamehere”).GetComponent().counter;

if this isn’t helping you, please post a bit more code, so we can evaluate.

Dear DrSnake,

Thank you for your solution, but isn’t helped.
Please check my project then you will see the problem.
(Click on all icons on the top one after another, you will see the layering problem.)
http://terberendezo.alexbutor.hu
user: a
pass: a

I got this error:
alapterulet.counterAT’ is inaccessible due to its protection level

This is my “B6” users button script:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class felhasznalo : MonoBehaviour {
  
    public GUIStyle userStyel;
    public GUIStyle userTooltipSytle;
    public GUIStyle szoveg;
    int counterAT=0;
  
//    string email = "";
//    string username = "";
//    string password = "";
//    string confirm = "";
  
    public enum Menu {
        MainMenu,
        NewGame,
        Continue
    }
  
    public Menu currentMenu;
    public List<Game> prefabLista = new List<Game>();



//    public void AddTarget(Transform savedPrefabTransform){
//        prefabLista.Add (new Game());  
//      
//    }



    void OnGUI () {
      

        if (counterAT==2)
        {
            counterAT = counterAT-2;
        }
      
        if (GUI.Button (new Rect (Screen.width/2+35, 10, 50, 48), "" ,userStyel))
        {
            counterAT++;
            Debug.Log(counterAT);  
        }
      
      
        if (counterAT == 1)
        {
        GUI.Box (new Rect (Screen.width / 2 - 200, 80, 405, 400), ""  ,userTooltipSytle);
            GUI.Label(new Rect(Screen.width / 2 - 170, 100, 60, 25), "FELHASZNÁLÓI FELÜLET" ,szoveg);
////            email = GUI.TextField (new Rect (Screen.width / 2 - 60, 135, 250, 25), email, 40);
////            username = GUI.TextField ( new Rect (Screen.width / 2 - 60, 170, 250, 25), username, 40);
////            password = GUI.PasswordField (new Rect (Screen.width / 2 - 60, 205, 250, 25), password, "*"[0], 40);
////            confirm = GUI.PasswordField (new Rect (Screen.width / 2 - 60, 240, 200, 25), confirm, "*"[0], 40);
//
            GUI.Label(new Rect(Screen.width / 2 - 170, 380, 60, 25), "Hamarosan elérhető!\n\n" +
                     "- árkalkulációt készíthet\n" +
                      "- megrendelését elküldheti\n" +
                      "- felhasználói adatokat módosíthat" ,szoveg);

//            if (GameObject.Find("B1").GetComponent<alapterulet>().counterAT)
//            {
//                //counterAT=0;
//            }
//
//
////            if (GUI.Button (new Rect (Screen.width / 2 - 60, 280, 100, 30), "Belépés")) {
////                Debug.Log(email + " " + username + " " + password + " " + confirm);



          
        //--------------------------------

            GUILayout.BeginArea(new Rect(Screen.width / 2 -170,150,200, 300));
//                GUILayout.BeginHorizontal();
//                GUILayout.FlexibleSpace();
//                GUILayout.BeginVertical();
//                GUILayout.FlexibleSpace();
              
                if(currentMenu == Menu.MainMenu) {
                  
                    GUILayout.Box("Térberendezés");
                    GUILayout.Space(10);
                  
                    if(GUILayout.Button("ÚJ üres tér")) {
                                                          
                        foreach(GameObject AllgameObjectsDelete in GameObject.FindGameObjectsWithTag("Player"))
                        {
                        Destroy (AllgameObjectsDelete);
                        }
                        currentMenu = Menu.MainMenu;


                    }

                    if(GUILayout.Button("Az összeállítás mentése")) {
                        Game.current = new Game();
                        currentMenu = Menu.NewGame;
                    }
                  
                    if(GUILayout.Button("Korábbi betöltése")) {
                        SaveLoad.Load();
                        currentMenu = Menu.Continue;
                    }

//                    if(GUILayout.Button("A lista törlése")) {
//                        SaveLoad.Load();
//                        Game gameToRemove = SaveLoad.savedGames.First<game>; //Replace with game you want to remove
//                        if (gameToRemove != null)
//                        {
//                        SaveLoad.savedGames.Remove(gameToRemove);
//                        }
//                        SaveLoad.Save();
//                        }


                }
              
                else if (currentMenu == Menu.NewGame) {
                  
                    GUILayout.Box("Személyes adatok");
                    GUILayout.Space(10);
                  
                    GUILayout.Label(("Az Ön neve"), szoveg);
                    Game.current.vezetek.name = GUILayout.TextField(Game.current.vezetek.name, 20);
                GUILayout.Label(("Az összeállítás megnevezése"), szoveg);
                    Game.current.osszeallitas.name = GUILayout.TextField(Game.current.osszeallitas.name, 20);

                  
                    if(GUILayout.Button("Mentés")) {
                        //Save the current Game as a new saved Game

      
                      

                        GameObject[]go = GameObject.FindGameObjectsWithTag("Player");  
                        foreach(GameObject AllgameObjectsSave in go)
                            {
                //            prefabLista.Add (new Game(AllgameObjectsSave.name));
                          
                            }
//                    foreach(GameObject AllgameObjectsSave in GameObject.FindGameObjectsWithTag("Player"))
//                    {
                    //    Game.current.savedPrefabName = AllgameObjectsSave.name;
                    //    prefabLista.Add (new Game(AllgameObjectsSave.name));
//                        prefabLista.Add (new Game(AllgameObjectsSave.transform));
                //        Game.current.savedPrefabName = AllgameObjectsSave.name;
//                        prefabLista.Add (new Game());
//                        Game.current.savedPrefabName.name = AllgameObjectsSave.name;
//                        prefabLista.Add(sPName);
//                        Debug.Log (AllgameObjectsSave.name);




//
//                    }

              


                        SaveLoad.Save();
                        //Move on to game...
                        //Application.LoadLevel(1);
                        currentMenu = Menu.MainMenu;
                    }
                  
                    GUILayout.Space(10);
                    if(GUILayout.Button("Vissza")) {
                        currentMenu = Menu.MainMenu;
                    }
                  
                }
              
                else if (currentMenu == Menu.Continue) {
                  
                    GUILayout.Box("Mentés kiválasztása");
                    GUILayout.Space(10);
                  
                    foreach(Game g in SaveLoad.savedGames) {
                        if(GUILayout.Button(g.vezetek.name + " - " + g.osszeallitas.name)) {
                        foreach(GameObject AllgameObjectsDelete in GameObject.FindGameObjectsWithTag("Player"))
                        {
                            Destroy (AllgameObjectsDelete);
                        }  
                        Game.current = g;
                    //    Instantiate (Resources.Load ("Prefabs/AS-A-8.6-F.E") as GameObject);
                    //    Debug.Log (Game.current.savedPrefabName.name);
                    //    Instantiate (Resources.Load ("Prefabs/"+Game.current.savedPrefabName.name));

                        //GameObject myObj = Instantiate (myObjects [whichItem]) as GameObject;
                            //Move on to game...
                            //Application.LoadLevel(1);
                          
                        }
                      
                    }
                  
                    GUILayout.Space(10);
                    if(GUILayout.Button("Vissza")) {
                        currentMenu = Menu.MainMenu;
                    }
                  
                }
              
//                GUILayout.FlexibleSpace();
//                GUILayout.EndVertical();
//                GUILayout.FlexibleSpace();
//                GUILayout.EndHorizontal();
                GUILayout.EndArea();
              
            }







          
          
              
      
        }
    }

That’s because ‘counterAt’ is private. You cannot access it from the outside without Reflection. You have three options:

  • Change the visibility of ‘counterAt’
  • Implement access methods (getters and setters)
  • Use runtime reflection
  1. changed in alapterulet script: public int counterAT=0;
    2th & 3th I don’t know, please help me, thanks.

2:
The reason why you use different visibilities (private, protected, internal, public) for your fields, classes, structs and enumerations is safety. You hide variables so they don’t exist for scripts that aren’t supposed to change them.
If you make everything public, you’re writing shitty code that is prone to error.

However, sometimes you want certain things to be readable from the outside. In that case you work with “Getters”. A getter is a function that simply returns a value (or reference).

public class A {
    private int number;

    //Getter for number
    public int GetNumber() {
        return number;
    }
}

public class B {
    private void A_Function() {
        A instance = new A();
        Debug.Log(instance.number); // doesn't work! number is private and inaccessible for B!
        Debug.Log(a.GetNumber()); // works! You can read number, but cannot change it!
}

A “Setter” is the same idea, but instead of returning a value (or reference) it changes it. They can be used to perform sanity checks of the values you’re trying to assign.

private int neverGreaterThanEleven;

public void SetNeverGreaterThanEleven(int value) {
    if(value > 11) {
        neverGreaterThanEleven = 11;
    }
    else {
        neverGreaterThanEleven = value;
    }
}

There are also more elegant ways to create this sort of behavior in C#, but that’s enough for a start. Wrap your head around this first. :wink:

3:
Runtime reflection is an advanced feature. Don’t bother looking into it, if you’re still new to programming. It’s powerful, but dangerous. It’s not something to be used lightly in game development.

Thank you for your solutions. The getter function is good for me.
I don’t understand the small “a” letter in the last Debug.Log.

I tried to check the number in A script, but I get this error:
The name `a’ does not exist in the current context

private void alapterulet_Function() {
alapterulet instance = new alapterulet();
Debug.Log(instance.counterAT); //doesn'twork! numberisprivateandinaccessibleforB!
Debug.Log(a.GetNumber()); //works! Youcanreadnumber, butcannotchangeit!


if (instance.counterAT == 1)
 {
counterFE = 0;
 }

// or -------------------------


if (a == 1)
{
counterFE = 0;
}

}

You’d have to post more of your code. Where do you declare (“create”) a?

Blah a = new Blah(); // for example

I think, very small thing is missing in my knowledge and if you solve that my mind will lighting up:)

First script: alapterulet // I need the counterAT

using UnityEngine;
using System.Collections;
using System.Text.RegularExpressions;

public class alapterulet : MonoBehaviour {
public int counterAT=0;
public int GetNumber() {return counterAT;}

void OnGUI () {



                if (counterAT==2)
                        {
                        counterAT = counterAT-2;
                        }
           
        if (GUI.Button (new Rect (Screen.width/2-265, 10, 50, 48), "" ,alapteruletStyle))
                {
                    counterAT++;
                Debug.Log("ButtonATpressed");
                }
           
           
                if (counterAT == 1)
                {
                 //something happening...
                }
}

Second script: felhasznalo // In this, if counterAT is changing, then change counterFE.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class felhasznalo : MonoBehaviour {

    public GUIStyle userStyel;
    public GUIStyle userTooltipSytle;
    public GUIStyle szoveg;
    public int counterFE=0;

private void alapterulet_Function() {
        alapterulet instance = new alapterulet();
        Debug.Log(instance.counterAT); //doesn'twork! numberisprivateandinaccessibleforB!
        Debug.Log(a.GetNumber()); //works! Youcanreadnumber, butcannotchangeit!
    
    
        if (instance.counterAT == 1)
        {
            counterFE = 0;
        }

void OnGUI () {
    

        if (counterFE==2)
        {
            counterFE = counterFE-2;
        }
    

        if (GUI.Button (new Rect (Screen.width/2+35, 10, 50, 48), "" , userStyel))
        {
            counterFE++;
            Debug.Log("ButtonFELpressed");
        }
    
    
        if (counterFE == 1)
        {
              //something happening...
               }
}

Hi,
I have solved that on other way, it is not so elegant, but working well.
I used the script in script call function.
Every script are on the same object, therefore I can select them very easily in public declaration.

public alapterulet caller1; // you need to select in the inspector the same object
public Inventory caller3; // you need to select in the inspector the same object
public ButorlapInventory caller4; // you need to select in the inspector the same object
public FemfestekInventory caller5; // you need to select in the inspector the same object
public felhasznalo caller6; // you need to select in the inspector the same object

...

if (counterME == 1)
{
caller1.helloAT ();
caller3.helloIN ();
caller4.helloBU ();
caller5.helloFEM ();
caller6.helloFEL ();
...

}

In “felhasznalo” script:

public void helloFEL(){
    
        counterFE = 0;

    }

If I add them in all script (lot of work), then will work what I want.
If you have time, check again my project.

One small thing: Use this instead:

[SerializeField]
private alapterulet caller1,
[SerializeField]
private ...