Textfield appear on MouseClick

Okay, so… I’m working on a game in Unity, where I got the brilliant (or not so brilliant) idea of adding level codes instead of the Save/Load system.

And since it’s my novice days of scripting, I’ve no idea how to make it work as it should… This is my script so far, so if someone could look at it, it’d be absolutely amazing.

var stringToEdit : String = "Enter Level Code";

function OnMouseEnter()
        {
                renderer.material.color = Color.red;
        }

function OnMouseExit()
        {
                renderer.material.color = Color.white;
        }
        
function OnMouseUp()
	{

		function OnGUI () {
    		// Make a text field that modifies stringToEdit.
    		stringToEdit = GUI.TextField (Rect (10, 10, 200, 20), stringToEdit, 25);
		}
}

What I’m trying to make it do… is change color, when the mouse enters the box collider (and that part works, I know), but I just don’t know how to make the last part work… I want to make the textbox pop up, when the boxcollider is clicked; and no, I won’t be converting a whole menu into GUI.

Much appreciated for the future help,

Azayah

Not sure how this build/compiles out, you are defining a function in a function to be used and executed like a function in a function. :frowning:

One method you can use is to add a boolean condition to the script like:

var stringToEdit : String = "Enter Level Code";
var openCodeText : boolean = false;

function OnMouseEnter()
{
	renderer.material.color = Color.red;
	openCodeText = true;
}
 
function OnMouseExit()
{
  renderer.material.color = Color.white;
  openCodeText = false;
}
 
function OnMouseUp()
{
 
}

function OnGUI () {
	// or the toggle button
	if (openCodeText) {
		// Make a text field that modifies stringToEdit.
		stringToEdit = GUI.TextField (Rect (10, 10, 200, 20), stringToEdit, 25);
		
		// Check to see if the user/player has pressed enter/return in the textfield.
		if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return)) {
                            // make the string the user entered lower because we can't check equality if it's mixed case... unless that is the case.
			switch (stringToEdit.ToLower())
			{
				case "banana":
					//load some level
					brea;
				case "apple":
					// load some other level
					break;
				default:
					break;
			}
		}
	}
}

In the case above, when the mouse enters it sets the bool var to true, when OnGUI is called from unity it will render the TextField, when the mouse leaves, it sets it to false and thus the subsequent calls to OnGUI will skip the GUI.TextField method.

If this doesn’t fit the functionality, adjust the placement of the boolean controlling the condition of the OnGUI controls draw.

EDIT per comment: check for enter/return event