Version: 5.5 (switch to 5.6b)
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

Method group is Obsolete

Screen.lockCursor

Obsolete public static bool lockCursor;

Description

Should the cursor be locked?

The cursor will automatically be hidden, centered on view and made to never leave the view.

After the user presses escape or switches to another application the cursor will be automatically unlocked. The cursor lock will also be lost when exiting full screen mode. You can query if the cursor is currently locked by checking the lockCursor state. To provide a good user experience it is recommended to only lock the cursor as a result of pressing a button. Also you should check if the cursor got unlocked, in order to e.g. pause the game or bring up a game menu. In the Editor the cursor will automatically be unlocked when you press escape. In the Standalone Player you have full control over mouse locking thus it won't automatically lose mouse lock unless you switch applications.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public GUITexture gt; void Start() { gt = GetComponent<GUITexture>(); } void DidLockCursor() { Debug.Log("Locking cursor"); gt.enabled = false; } void DidUnlockCursor() { Debug.Log("Unlocking cursor"); gt.enabled = true; } void OnMouseDown() { Screen.lockCursor = true; } private bool wasLocked = false; void Update() { if (Input.GetKeyDown("escape")) Screen.lockCursor = false; if (!Screen.lockCursor && wasLocked) { wasLocked = false; DidUnlockCursor(); } else if (Screen.lockCursor && !wasLocked) { wasLocked = true; DidLockCursor(); } } }