GUI Script Fix

Its been a while since I used unity and I’ve got a problem with a script. I cant seem to figure out how to fix it. Here’s the code. It should make a message pop up when you close enough and press E, but when I press E the msgbox variable stays false.

var tombstyle : GUIStyle;
var target : GameObject;
var message : String;
var msgbox = false;

function Update () {
	distance = Vector3.Distance(target.transform.position, transform.position);
	if(msgbox == false && distance <= 3.0 && Input.GetKeyUp(KeyCode.E))
		{
		msgbox = true;
		}
	if(msgbox == true && Input.GetKeyUp(KeyCode.E))
		{
			msgbox = false;
		}
	}
	

function OnGUI()
	{
	if(msgbox == true)
		{
		GUI.Box(Rect(Screen.height / 10 * 9.5, Screen.width / 10 * 9.5, Screen.height / 10 * 9, Screen.width / 10 * 9), message, tombstyle);
		}
	}

The second if statement is true immediately after the first was true and sets the message box back to false. Use else if and it should work.

(I had the same problem with my main menu and the Esc key ;))

You should calculate the distance only when E is pressed. Squarre roots are expensive, no use calculating them each frames.

Now, use print to find why msgbox doesn’t get enabled.