- Home /
=true then =false then back to true
this is in my pause menu to lock the cursor to the center but when i press escape free it for a bit to press option buttons then when i press escape again to lock it to the center again,what arent i doing?
var SwitchOnSound:AudioClip;
var SwitchOffSound:AudioClip;
private var Off : boolean = false;
private var On : boolean = true;
function Start () {
Screen.lockCursor = true;
}
function Update()
{
if(Screen.lockCursor)
{
if(Off)
{
if(Input.GetKeyDown(KeyCode.Escape))
{
On = true;
Off = false;
AudioSource.PlayClipAtPoint(SwitchOnSound, transform.position);
}
}
else
{
if(On)
{
if(Input.GetKeyDown(KeyCode.Escape))
{
On = false;
Off = true;
AudioSource.PlayClipAtPoint(SwitchOffSound, transform.position);
}
}
}
}
}
The first thing I notice is the entire block of if statements only runs if the cursor is locked. You also might as well just use one boolean with a name such as 'is_enabled', there is no point having two booleans to change one other.
private var lock_cursor : boolean = false;
function Update(){
Screen.lockCursor = lock_cursor;
if(Input.Get$$anonymous$$eyDown("escape")){
AudioSource.PlayClipAtPoint((lock_cursor) ? OffSound : OnSound, transform.position);
lock_cursor = !lock_cursor;
}
}
Just in case you don't know the ternary operator will evaluate what's in the parenthesis and return the first value if it is true and the second if it is false, in this case a simple way of playing the two toggle sounds without having if statements.
Answer by Olgo · Jan 15, 2014 at 12:34 AM
Seems to me you aren't toggling your Screen.lockCursor at any point, it always == true;
I don't know what your entire project entails and what you use On and Off for, but seems to me you could really simplify this.
if(Input.GetKeyDown(Keycode.Escape)){
Screen.lockCursor = !Screen.lockCursor
if(Screen.lockCursor)
AudioSource.PlayClipAtPoint(SwitchOffSound, transform.position);
else
AudioSource.PlayClipAtPoint(SwitchOnSound, transform.position);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613130447im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
scripting is not working for words "true" & "false" 1 Answer
Fixed error but error still shows in the console 2 Answers
Could someone fix this : It says expressions must only be executed ofr their side-effects 1 Answer
Copy rotation values in between objects. 1 Answer
Setting Scroll View Width GUILayout 1 Answer