Only using related functions, yet still being told that I can't use non GUI functions in OnGUI (Don't call OnGUI)

I have a in game pause menu triggered when pressing escape, called using


if (Input.GetKeyDown(KeyCode.Escape)) {
    isPaused = true;

if (isPaused == true) {
	mouseLook.enabled = false;
	motionControl.enabled = false;
	OnGUI ();

Which then calls OnGUI. The error, ArgumentException: You can only call GUI functions from inside OnGUI occurs within the OnGUI with the stacktrace? pointing in the bottom 2 lines to: on the second from bottom line, the GUILayout.BeginArea line within the OnGUI function; on the bottom most line, where the OnGUI is called in the code above.

I have a feeling it’s the GUILayout.BeginArea line, which uses Screen.width and Screen.height. I think the error is referring to the use of the Screen class?, which I am using to center the GUI on the screen. Code for the entire OnGUI is as follows:



 function OnGUI () {
	if (isPaused == true) {
		GUILayout.BeginArea(Rect((Screen.width / 2) - Screen.width / 4,(Screen.height / 2) - Screen.height / 4,Screen.width / 2,Screen.height / 2));
				if (GUILayout.Button(returnMessage)) {
					mouseLook.enabled = true;
					motionControl.enabled = true;
					isPaused = false;
// This area is commented out because it doesn't work
//				if (Input.GetKeyDown(KeyCode.Escape)) {
//					mouseLook.enabled = true;
//					motionControl.enabled = true;
//					isPaused = false;
//				}
				if (GUILayout.Button(returnToMainMenuMessage)) {
				if (GUILayout.Button(quitMessage)) {

Full Error Code (the copyable part):


ArgumentException: You can only call GUI functions from inside OnGUI.
UnityEngine.GUIUtility.CheckOnGUI () (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUIUtility.cs:228)
UnityEngine.GUILayout.BeginArea (Rect screenRect, UnityEngine.GUIContent content,     UnityEngine.GUIStyle style) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUILayout.cs:281)
UnityEngine.GUILayout.BeginArea (Rect screenRect) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUILayout.cs:270)
InGamePauseMenu.OnGUI () (at Assets/Scripts/InGamePauseMenu.js:38)
InGamePauseMenu.Update () (at Assets/Scripts/InGamePauseMenu.js:32) `

All refenced code is located in the InGamePauseMenu script, testing for escape in in Update function, OnGUI is OnGUI. Line 38 in the GUILayout.BeginArea line and line 32 is where OnGUI (); is called in the first referenced section of code (update function).


TL;DR: I think the error occured because of using Screen.width and Screen.height in the rectangle define area of GUILayout.BeginArea

EDIT: You don’t call OnGUI

I don’t think you can call “OnGUI” in that way (ie top script line 8, remove that) and there’s no need, OnGUI runs many many times a frame

Edit: glad that did it, changed to Answer.