Ingame Menu Problems

Hello, so I’m working on a simple in game menu, and i ran into a couple of problems, ive searched around the forum but didnt seem to find a fix for this certain issue, and im sure others came across it too.

I used the script from this site just to get started… http://www.unifycommunity.com/wiki/index.php?title=PauseMenu It seems to work quite well, except while im in pause mode, im still able to look around, and im able to equip weapon, and im able to shoot just 1 time.

I know that the pause function only makes the timescale to 0 so that it freezes the game, but how do i freeze the player’s ability to look around/equip stuff?

Its a long and very ugly code to look at, but ill post it anyway…

var skin:GUISkin;

private var gldepth = -0.5;
private var startTime = 0.1;

var mat:Material;

private var tris = 0;
private var verts = 0;
private var savedTimeScale:float;
private var pauseFilter;

private var showfps:boolean;
private var showtris:boolean;
private var showvtx:boolean;
private var showfpsgraph:boolean;

var lowFPSColor = Color.red;
var highFPSColor = Color.green;

var lowFPS = 25;
var highFPS = 50;

var start:GameObject;

var url = "unity.html";

var statColor:Color = Color.yellow;

var credits:String[]=[""] ;
var crediticons:Texture[];

enum Page {
    None,Main,Options,Credits
}

private var currentPage:Page;

private var fpsarray:int[];
private var fps:float;

function Start(){
 Time.timeScale = 1;
 Screen.showCursor = false; //(hides the cursor)
 }

function OnPostRender() {
    if (showfpsgraph  mat != null) {
        GL.PushMatrix ();
        GL.LoadPixelMatrix();
        for (var i = 0; i < mat.passCount; ++i)
        {
            mat.SetPass(i);
            GL.Begin( GL.LINES );
            for (var x=0; x<fpsarray.length; ++x) {
                GL.Vertex3(x,fpsarray[x],gldepth);
            }
        GL.End();
        }
        GL.PopMatrix();
        ScrollFPS();
    }
}

function ScrollFPS() {
    for (var x=1; x<fpsarray.length; ++x) {
        fpsarray[x-1]=fpsarray[x];
    }
    if (fps < 1000) {
        fpsarray[fpsarray.length-1]=fps;
    }
}

static function IsDashboard() {
    return Application.platform == RuntimePlatform.OSXDashboardPlayer;
}

static function IsBrowser() {
    return (Application.platform == RuntimePlatform.WindowsWebPlayer ||
        Application.platform == RuntimePlatform.OSXWebPlayer);
}

function LateUpdate () {

    if (showfps || showfpsgraph) {
        FPSUpdate();
    }
    if (Input.GetKeyDown("escape")) {
        switch (currentPage) {
            case Page.None: SetPause(); break;
            case Page.Main: if (!IsBeginning()) UnSetPause(); break;
            default: currentPage = Page.Main;
        }
    }
}

function OnGUI () {

    if (skin != null) {
        GUI.skin = skin;
    }
    ShowStatNums();
    ShowLegal();
    if (IsGamePaused()) {
        GUI.color = statColor;
        switch (currentPage) {
            case Page.Main: Pause(); break;
            case Page.Options: ShowToolbar(); break;
        }
    }   
}

function ShowLegal() {
    if (!IsLegal()) {
        GUI.Label(Rect(Screen.width-100,Screen.height-20,90,20),
        "fugugames.com");
    }
}

function IsLegal() {
    return !IsBrowser() || 
    Application.absoluteURL.StartsWith("http://www.fugugames.com/") ||
    Application.absoluteURL.StartsWith("http://fugugames.com/");
}

private var toolbarInt:int=0;
private var toolbarStrings: String[]= ["Settings","Graphic","Stats","System"];

function ShowToolbar() {
    BeginPage(425,350);
    toolbarInt = GUILayout.Toolbar (toolbarInt, toolbarStrings);
    switch (toolbarInt) {
        case 0: VolumeControl(); break;
        case 3: ShowDevice(); break;
        case 1: Qualities(); QualityControl(); break;
        case 2: StatControl(); break;
    }
    EndPage();
}

function ShowCredits() {
    BeginPage(300,300);
    for (var credit in credits) {
        GUILayout.Label(credit);
    }
    for (var credit in crediticons) {
        GUILayout.Label(credit);
    }
    EndPage();
}

function ShowBackButton() {
    if (GUI.Button(Rect(20,Screen.height-50,50,20),"Back")) {
        currentPage = Page.Main;
    }
}

function ShowDevice() {
    GUILayout.Label ("Unity player version "+Application.unityVersion);
    GUILayout.Label("Graphics: "+SystemInfo.graphicsDeviceName+" "+
    SystemInfo.graphicsMemorySize+"MB\n"+
    SystemInfo.graphicsDeviceVersion+"\n"+
    SystemInfo.graphicsDeviceVendor);
    GUILayout.Label("Shadows: "+SystemInfo.supportsShadows);
    GUILayout.Label("Image Effects: "+SystemInfo.supportsImageEffects);
    GUILayout.Label("Render Textures: "+SystemInfo.supportsRenderTextures);
}

function Qualities() {
    switch (QualitySettings.currentLevel) {
        case QualityLevel.Fastest:
        GUILayout.Label("Fastest");
        break;
        case QualityLevel.Fast:
        GUILayout.Label("Fast");
        break;
        case QualityLevel.Simple:
        GUILayout.Label("Simple");
        break;
        case QualityLevel.Good:
        GUILayout.Label("Good");
        break;
        case QualityLevel.Beautiful:
        GUILayout.Label("Beautiful");
        break;
        case QualityLevel.Fantastic:
        GUILayout.Label("Fantastic");
        break;
    }
}

function QualityControl() {
    GUILayout.BeginHorizontal();
    if (GUILayout.Button("Decrease")) {
        QualitySettings.DecreaseLevel();
    }
    if (GUILayout.Button("Increase")) {
        QualitySettings.IncreaseLevel();
    }
    GUILayout.EndHorizontal();
}

function VolumeControl() {
    GUILayout.Label("Volume");
    AudioListener.volume = GUILayout.HorizontalSlider(AudioListener.volume,0.0,1.0);
}

function StatControl() {
    GUILayout.BeginHorizontal();
    showfps = GUILayout.Toggle(showfps,"FPS");
    GUILayout.EndHorizontal();
}

function FPSUpdate() {
    var delta = Time.smoothDeltaTime;
        if (!IsGamePaused()  delta !=0.0) {
            fps = 1 / delta;
        }
}

function ShowStatNums() {
    GUILayout.BeginArea(Rect(Screen.width-100,10,100,200));
    if (showfps) {
        var fpsString= fps.ToString ("#,##0 fps");
        GUI.color = Color.Lerp(lowFPSColor, highFPSColor,(fps-lowFPS)/(highFPS-lowFPS));
        GUILayout.Label (fpsString);
    }
    if (showtris || showvtx) {
        GetObjectStats();
        GUI.color = statColor;
    }
    if (showtris) {
        GUILayout.Label (tris+"tri");
    }
    if (showvtx) {
        GUILayout.Label (verts+"vtx");
    }
    GUILayout.EndArea();
}

function BeginPage(width,height) {
    GUILayout.BeginArea(Rect((Screen.width-width)/2,(Screen.height-height)/2,width,height));
}

function EndPage() {
    GUILayout.EndArea();
    if (currentPage != Page.Main) {
        ShowBackButton();
    }
}

function IsBeginning() {
    return Time.time < startTime;
}

function Pause() {

 Screen.showCursor = true; //(shows the cursor)
 
 if (Input.GetKeyDown("escape")) {
 Screen.showCursor = false; //(hides the cursor)
 }
    BeginPage(250,250);
    if (GUILayout.Button (IsBeginning() ? "Resume" : "Resume")) {
        UnSetPause();
		 Screen.showCursor = false; //(hides the cursor)
		}

    if (GUILayout.Button ("Options")) {
        currentPage = Page.Options;
    }
	
       if (GUILayout.Button ("Quit To Main Menu")) {
		Application.LoadLevel("MainMenu");
    }
	
if (GUILayout.Button ("Quit To Windows")) {
		Application.Quit();
    }

    if (IsBrowser()  !IsBeginning()  GUILayout.Button ("Restart")) {
        Application.OpenURL(url);
    }
    EndPage();
}

function GetObjectStats() {
    verts = 0;
    tris = 0;
    var ob = FindObjectsOfType(GameObject);
    for (var obj in ob) {
        GetObjectStats(obj);
    }
}

function GetObjectStats(object) {
    var filters : Component[];
    filters = object.GetComponentsInChildren(MeshFilter);
    for( var f : MeshFilter in filters )
    {
        tris += f.sharedMesh.triangles.Length/3;
      verts += f.sharedMesh.vertexCount;
    }
}

function SetPause() {
//Screen.lockCursor = true; //ShowCursor
    savedTimeScale = Time.timeScale;
    Time.timeScale = 0;
    AudioListener.pause = true;
    if (pauseFilter) pauseFilter.enabled = true;
    currentPage = Page.Main;
}

function SetPause (pause : boolean)
{
	Input.ResetInputAxes();
	var gos : Object[] = FindObjectsOfType(GameObject);
	for (var go : GameObject in gos)
		go.SendMessage("DidPause", pause, SendMessageOptions.DontRequireReceiver);
	
	transform.position = Vector3.zero;
	
	if (pause)
	{
		Time.timeScale = 0;
		transform.position = Vector3 (.5, .5, 0);
		guiText.anchor = TextAnchor.MiddleCenter;
	}
	else
	{
		guiText.anchor = TextAnchor.UpperLeft;
		transform.position = Vector3(0, 1, 0);
		Time.timeScale = 1;
	}
}

function UnSetPause() {
    Time.timeScale = savedTimeScale;
    AudioListener.pause = false;
    if (pauseFilter) pauseFilter.enabled = false;
    currentPage = Page.None;
    if (IsBeginning()  start != null) {
        start.active = true;
    }
}

function IsGamePaused() {
    return Time.timeScale==0;
}

function OnApplicationPause(pause:boolean) {
    if (IsGamePaused()) {
        AudioListener.pause = true;
    }
}

function OnMouseDown ()
{
 Screen.showCursor = false; //(hides the cursor)
}

One generally early exits input routines and anything else relevant. You could do this keying off of the current physics timescale, but it would make things a lot easier to maintain if you drove it with your game’s state machine giving you a human readable variable.

if (gameIsPaused)
 return;

edit: Was there a GUI question in there somewhere I missed?

I didnt really get what you said, but I saw that little code you added, does that matter where i stick it in? I could put it in any function right?

And no, you didnt miss anything else, I actually edited my post several times because i fixed things myself.

Uhh i tried putting this in every different function, and they all dont work, either pause stops working, or i cant move at all… Its suppose to be

	if (IsGamePaused) 
 return;

But i dont know where to put it…

You could put this in the GUI or anywhere appropriate to stop activity when the game is paused. For example:-

function OnGUI() {
    if (IsGamePaused) 
        return;

       //GUI code...
}

…will abort the OnGUI function before anything is displayed.

It doesnt seem to work, when i play, and press escape to pause, nothing happens, it totally disables the pause option, whats wrong?

Well to make it a little easier, I decided to put a background on the ingame menu, so the player cant look around, problem is if i click anywhere during the ingame menu, im still aboe to shoot atleast once, and use other functionalities, basically any key on the keyboard, is there a way to disable this during the pause menu?

This is the updated code:

var skin:GUISkin;

private var gldepth = -0.5;
private var startTime = 0.1;

var mat:Material;

private var tris = 0;
private var verts = 0;
private var savedTimeScale:float;
private var pauseFilter;

private var showfps:boolean;
private var showtris:boolean;
private var showvtx:boolean;
private var showfpsgraph:boolean;

var MenuMusic : AudioClip;

var lowFPSColor = Color.red;
var highFPSColor = Color.green;

var backdrop : Texture2D; // our backdrop image goes in here.

var lowFPS = 25;
var highFPS = 50;

var start:GameObject;

var url = "unity.html";

var statColor:Color = Color.yellow;

var credits:String[]=[""] ;
var crediticons:Texture[];

enum Page {
    None,Main,Options,Credits
}

private var currentPage:Page;

private var fpsarray:int[];
private var fps:float;

function Start(){

 Time.timeScale = 1;
 Screen.showCursor = false; //(hides the cursor)
 }

function OnPostRender() {
    if (showfpsgraph  mat != null) {
        GL.PushMatrix ();
        GL.LoadPixelMatrix();
        for (var i = 0; i < mat.passCount; ++i)
        {
            mat.SetPass(i);
            GL.Begin( GL.LINES );
            for (var x=0; x<fpsarray.length; ++x) {
                GL.Vertex3(x,fpsarray[x],gldepth);
            }
        GL.End();
        }
        GL.PopMatrix();
        ScrollFPS();
    }
}

function ScrollFPS() {
    for (var x=1; x<fpsarray.length; ++x) {
        fpsarray[x-1]=fpsarray[x];
    }
    if (fps < 1000) {
        fpsarray[fpsarray.length-1]=fps;
    }
}

static function IsDashboard() {
    return Application.platform == RuntimePlatform.OSXDashboardPlayer;
}

static function IsBrowser() {
    return (Application.platform == RuntimePlatform.WindowsWebPlayer ||
        Application.platform == RuntimePlatform.OSXWebPlayer);
}

function LateUpdate () {

 if (Input.GetKeyDown("escape")  Pause) {
 audio.Stop();
 }

    if (Input.GetKeyDown("escape")) {

        switch (currentPage) {
            case Page.None: SetPause(); break;
            case Page.Main: if (!IsBeginning()) UnSetPause(); break;
            default: currentPage = Page.Main;

        }
    }
}

function OnGUI () {

if(currentPage == Page.Options){
var backgroundStyle : GUIStyle = new GUIStyle();
			backgroundStyle.normal.background = backdrop;
GUI.Label ( Rect( (Screen.width - (Screen.height * 2))* 0.75, 0, Screen.height*2,Screen.height), "" , backgroundStyle);
}

    if (skin != null) {
        GUI.skin = skin;
    }
    ShowLegal();
    if (IsGamePaused()) {
     //   GUI.color = statColor;
        switch (currentPage) {
            case Page.Main: Pause(); break;
            case Page.Options: ShowToolbar(); break;
        }
    }   
}

function ShowLegal() {
    if (!IsLegal()) {
        GUI.Label(Rect(Screen.width-100,Screen.height-20,90,20),
        "fugugames.com");
    }
}

function IsLegal() {
    return !IsBrowser() || 
    Application.absoluteURL.StartsWith("http://www.fugugames.com/") ||
    Application.absoluteURL.StartsWith("http://fugugames.com/");
}

private var toolbarInt:int=0;
private var toolbarStrings: String[]= ["Audio","Graphics"];

function ShowToolbar() {
    BeginPage(450,300);
    toolbarInt = GUILayout.Toolbar (toolbarInt, toolbarStrings);
    switch (toolbarInt) {
        case 0: VolumeControl(); break;
        case 1: Qualities(); QualityControl(); break;
    }
    EndPage();
}

function ShowCredits() {
    BeginPage(300,250);
    for (var credit in credits) {
        GUILayout.Label(credit);
    }
    for (var credit in crediticons) {
        GUILayout.Label(credit);
    }
    EndPage();
}

function ShowBackButton() {
    if (GUI.Button(Rect(20,Screen.height-50,80,40),"Back")) {
        currentPage = Page.Main;
    }
}

function Qualities() {
    switch (QualitySettings.currentLevel) {
        case QualityLevel.Fastest:
		GUILayout.Label("");
        GUILayout.Label("Lowest");
		GUILayout.Label("");
        break;
        case QualityLevel.Fast:
		GUILayout.Label("");
        GUILayout.Label("Low");
		GUILayout.Label("");
        break;
        case QualityLevel.Simple:
		GUILayout.Label("");
        GUILayout.Label("Middle");
		GUILayout.Label("");
        break;
        case QualityLevel.Good:
		GUILayout.Label("");
        GUILayout.Label("Higher");
		GUILayout.Label("");
        break;
        case QualityLevel.Beautiful:
		GUILayout.Label("");
        GUILayout.Label("Highest");
		GUILayout.Label("");
        break;
        case QualityLevel.Fantastic:
		GUILayout.Label("");
        GUILayout.Label("Ultra");
		GUILayout.Label("");
        break;
    }
}

function QualityControl() {
   GUILayout.BeginHorizontal();
	 
    if (GUILayout.Button("Decrease")) {
        QualitySettings.DecreaseLevel();
    }
    if (GUILayout.Button("Increase")) {
        QualitySettings.IncreaseLevel();
    }
    GUILayout.EndHorizontal();
}

function VolumeControl() {
    GUILayout.Label("");
    GUILayout.Label("Master Volume");
	GUILayout.Label("");
    AudioListener.volume = GUILayout.HorizontalSlider(AudioListener.volume,0.0,1.0);
}

function BeginPage(width,height) {
    GUILayout.BeginArea(Rect((Screen.width-width)/2,(Screen.height-height)/2,width,height));
}

function EndPage() {
    GUILayout.EndArea();
    if (currentPage != Page.Main) {
        ShowBackButton();
    }
}

function IsBeginning() {
    return Time.time < startTime;
}

function Pause() {

audio.PlayOneShot(MenuMusic, 1.0 / audio.volume);
	
    Time.timeScale = 0;

 var backgroundStyle : GUIStyle = new GUIStyle();
backgroundStyle.normal.background = backdrop;
GUI.Label ( Rect( (Screen.width - (Screen.height * 2))* 0.75, 0, Screen.height*2,Screen.height), "" , backgroundStyle);

 Screen.showCursor = true; //(shows the cursor)
 
 if (Input.GetKeyDown("escape")) {
 Screen.showCursor = false; //(hides the cursor)
 }
 
    BeginPage(300,300);
    if (GUILayout.Button (IsBeginning() ? "Resume" : "Resume")) {
        UnSetPause();
		 Screen.showCursor = false; //(hides the cursor)
		  audio.Stop();
		}

    if (GUILayout.Button ("Options")) {
        currentPage = Page.Options;
		
    }
	
       if (GUILayout.Button ("Quit To Main Menu")) {
		Application.LoadLevel("MainMenu");
    }
	
if (GUILayout.Button ("Quit To Windows")) {
		Application.Quit();
    }

    if (IsBrowser()  !IsBeginning()  GUILayout.Button ("Restart")) {
        Application.OpenURL(url);
    }
    EndPage();
}

function SetPause() {

    savedTimeScale = Time.timeScale;
    Time.timeScale = 0;
    AudioListener.pause = true;
    if (pauseFilter) pauseFilter.enabled = true;
    currentPage = Page.Main;
}

function SetPause (pause : boolean)
{

	Input.ResetInputAxes();
	var gos : Object[] = FindObjectsOfType(GameObject);
	for (var go : GameObject in gos)
		go.SendMessage("DidPause", pause, SendMessageOptions.DontRequireReceiver);
	
	transform.position = Vector3.zero;
	
	if (pause)
	{
		Time.timeScale = 0;
		transform.position = Vector3 (.5, .5, 0);
		guiText.anchor = TextAnchor.MiddleCenter;
	}
	else
	{
		guiText.anchor = TextAnchor.UpperLeft;
		transform.position = Vector3(0, 1, 0);
		Time.timeScale = 1;
	}
}

function UnSetPause() {
    Time.timeScale = savedTimeScale;
    AudioListener.pause = false;
    if (pauseFilter) pauseFilter.enabled = false;
    currentPage = Page.None;
    if (IsBeginning()  start != null) {
        start.active = true;
    }
}

function IsGamePaused() {

    return Time.timeScale==0;
}

function OnApplicationPause(pause:boolean) {
    if (IsGamePaused()) {
        AudioListener.pause = true;
    }
}

function OnMouseDown ()
{
 Screen.showCursor = false; //(hides the cursor)
}

We’ve already answered this question. You disable those functions by disabling them when the game is paused. Is the game paused? Early exit the input routines.

It’s a simple concept conceptually. How do you turn the lights off when you leave the room? Obviously by turning the lights off when you leave the room!

Sorry but how do I disable functions, and which functions am I suppose to disable? Please bare with me, I’m still trying to get a hang of javascript…

I used… um… let me gather my thoughts…

I used this if the component was in another object…

GameObject.Find("object").GetComponent("component").enabled = false;

then set it to true when paused was off.

That should work pretty easily unless you have a bunch running at the same time…

Okay let me plug that into the script and lets see what it does.

Well when I added it into the pause function, when i press escape to pause, the menu doesnt show, and it gives a long error. It does pause but it doesnt show the options, and im still able to change weapons and shoot and use any keyboard functionality…

NullReferenceException
UnityEngine.GameObject.GetComponent (System.String type) 
menu.Pause ()   (at Assets\MainMenuAssets\menu.js:240)
menu.OnGUI ()   (at Assets\MainMenuAssets\menu.js:120)
UnityEditor.EditorGUIUtility:RenderGameViewCameras(Rect, Rect, Boolean, Boolean)
UnityEditor.EditorGUIUtility:RenderGameViewCameras(Rect, Rect, Boolean, Boolean)
UnityEditor.GameView:OnGUI()
System.Reflection.MonoMethod:InternalInvoke(Object, Object[])
System.Reflection.MonoMethod:InternalInvoke(Object, Object[])
System.Reflection.MonoMethod:Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
System.Reflection.MethodBase:Invoke(Object, Object[])
UnityEditor.HostView:Invoke(String)

i think andeee meant that you should make “IsGamePaused” like a static variable ? and then in the first line of … ye whatever script you want to stop, you put it at the first line.

//random function

function RotateCamera() {
    if (MyScriptName.IsGamePaused)
        return;

Edit*
Else you can use the Disable Component. but you got a null reference exception error, so it seems you just wrote something wrong.

I have a function for isGamePaused, and it does return by the looks of it.

function IsGamePaused() {
   return Time.timeScale==0;
}

Wont that cut it? I noticed that in the offical fps tutorial, if you pause, the player isnt able to look around or anything, but when you change things like I did for my game, your somehow able to look around during pause, its really odd to me.

The timescale just changes things affected by time.
you have to manually disable components, in one or another way to stop those who are not affected by time.

i havent looked in the fps tutorial, but i did it myself with a disable component. like the one mentioned by Tigerson.

But what components am I suppose to disable? Nothing in this script controls player movement/mouse movement. I know I need to change the components in “GameObject.Find(“object”).GetComponent(“component”).enabled = false;” but Im just not sure which ones.

I put that little bit of script in the IsGamePaused function and I got a notice saying the code is unreachable.

Assets/MainMenuAssets/menu.js(326,64): BCW0015: WARNING: Unreachable code detected.

GameObject.Find("Player")GetComponent(MouseLook).enabled = false;

in this case, the object your searching for gotta be named “Player” and if it finds the component “MouseLook” in “Player” it will disable it.
if its in a child of the gameobject “Player”, you gotta use GetComponentInChildren… etc

you can find all this on the Script Reference site, with examples and all…

you dont seem familiar with that gui script, so you should probably test this outside that script.so you can debug it properly or something…

Ohh i see now, this makes more sense to me, I managed to disable the player mouse but only for the Y axis which is fine because its covered by an image.

Just one last thing, you said I must use GetComponentsInChildren to get scripts from the child of the player, I used this script:GameObject.Find("FirstPersonPlayer").GetComponentsInChildren("Gun").enabled = false;
and i get this error

if you are using GetComponentsInChildren, you cant use the “” when your searching component.

i dont know why they wrote it that way … but like this :

GameObject.Find("Player")GetComponentsInChildren(RandomScriptName).enabled = false;

oh and btw GetComponents and GetComponent, is not the same thing… so i dont know if they have the same syntax. search for these kind of things on Unity’s Script Reference site.

Hah thats quite odd, but great news, it works! Ive disabled almost everything that requires movement from the player, so now it pauses exactly how I want, thanks SO much guys :slight_smile: