Unity: Detect GUI Window Created/Closed Event


On StackOverflow, someone asks how to detect the GUI Window Created/Closed Event, which Unity3D does not ship an off-the-shelf solution.

Below is my solution to this problem: to use property setter to handle this. Here is the sample code:

enter image description here

bool _bWindowActive;
public bool bWindowActive {
	get { return _bWindowActive;}
	set { 
		_bWindowActive = value;
		if (bWindowActive) {
		// This is called everytime, when bWindowActive = true;
		OnWindowInited ();  
		}
		if (!bWindowActive) {
		// This is called everytime, when bWindowActive = false;
		OnWindowClosed ();  
		}
	}
}

public void OnWindowInited ()
{
	Debug.Log ("Windows Inited");
}

public void OnWindowClosed ()
{
	Debug.Log ("Windows Closed");
}

public void OnGUI() {

	if (GUI.Button (new Rect (10, 20, 100, 20), "Show Window")) {
		if(!bWindowActive)
			bWindowActive = true;
	}
	if (GUI.Button (new Rect (10, 60, 100, 20), "Close Window")) {
		if(bWindowActive)
			bWindowActive = false;
	}
	if (bWindowActive) {
		GUI.Window (0, new Rect(200, 10, 200, 200), 
DoMyWindow, "My Window"); } } public void DoMyWindow(int windowID) { if (GUI.Button (new Rect (10,20,100,20), "Hello World")) print ("Got a click"); }

Happy coding!

Leave a comment