- Home /
Mouse wont relock
Hi, i am working on a building game and i want to have a menu where you can select items. the mouse starts off locked when i press e(the inventory button) it unlocks like its supposed to but when i press e again the gui goes away(like it should) but the mouse stays unlocked.
Code: (Its no where near complete and may seem sloppy to you guys)
#pragma strict
//values
private var showGui : boolean = false;
private var invopen : boolean = false;
//lock mouse
var mouselocked : boolean = true;
//player
var player : Transform;
//blocks and items
var buildingplatform : Transform;
//messy code
function Update()
{
if (Input.GetKeyDown ("e")){
if (invopen == true)
{
invopen = false;
mouselocked = true;
}
else
invopen = true;
mouselocked = false;
}
if (mouselocked == true)
{
Screen.lockCursor = true;
}
if (mouselocked == false)
{
Screen.lockCursor = false;
}
if(Input.GetKey("p"))
{
spawnbuildingplatform();
}
}
function OnGUI()
{
if (invopen == true)
{
GUI.Box(new Rect(200, 200, 200, 200), "Spawn Menu");
}
}
function spawnbuildingplatform()
{
Instantiate (buildingplatform, player.transform.position, Quaternion.identity);
showGui = false;
}
Answer by Kiwasi · Jul 06, 2014 at 04:13 AM
You need {} around the code block you use for the else on lines 32 and 33. While it is possible to use an if or else without the brackets is highly recommended against, for this reason.
If you don't have the curly brackets the else clause will only include the next line. Unity interprets it like this:
if (Input.GetKeyDown ("e")){
if (invopen == true)
{
invopen = false;
mouselocked = true;
} else {
invopen = true;
}
mouselocked = false;
}
What you want is this
if (Input.GetKeyDown ("e")){
if (invopen == true)
{
invopen = false;
mouselocked = true;
} else {
invopen = true;
mouselocked = false;
}
}
That didn't work. it actually made it worse now the gui is always open and the mouse never locks. Thanks anyway. :(
That wasn't my intent. Can you post the new script? Are you sure all the {} are in the right place?
#pragma strict
//values
private var showGui : boolean = false;
private var invopen : boolean = false;
//lock mouse
var mouselocked : boolean = true;
//player
var player : Transform;
//blocks and items
var buildingplatform : Transform;
//messy code
function Update()
{
if (Input.Get$$anonymous$$eyDown ("e")){
if (invopen == true)
{
invopen = false;
mouselocked = true;
}
}else{
invopen = true;
mouselocked = false;
}
if (mouselocked == true)
{
Screen.lockCursor = true;
}
if (mouselocked == false)
{
Screen.lockCursor = false;
}
if(Input.Get$$anonymous$$ey("p"))
{
spawnbuildingplatform();
}
}
function OnGUI()
{
if (invopen == true)
{
GUI.Box(new Rect(200, 200, 200, 200), "Spawn $$anonymous$$enu");
}
}
function spawnbuildingplatform()
{
Instantiate (buildingplatform, player.transform.position, Quaternion.identity);
showGui = false;
}
Throw an extra } on line 34. Delete the one at the start of line 30.