Version: 2023.2
Method group is Obsolete

Screen.lockCursor

切换到手册
Obsolete public static bool lockCursor ;

描述

Enable cursor locking

By default, when this property is enabled, the cursor is automatically hidden, centered on view and made to never leave the view.

用户按下 ESC 键或切换到其他应用程序后,将自动解锁光标。 退出全屏模式时,也将解除光标锁定。 可以通过检查 lockCursor 状态来查询当前是否锁定了光标。 为了提供良好的用户体验,建议仅在按下按钮时锁定光标。 此外,您还应该检查是否解锁了光标,以便暂停游戏、调出游戏菜单等。 在 Editor 中,按下 ESC 键后,将自动解锁光标。 在独立平台播放器中,您可以全权控制鼠标锁定,因此,除非切换应用程序,否则不会自动解除鼠标锁定。

using UnityEngine;
using UnityEngine.UI;

public class Example : MonoBehaviour { Button bt; bool wasLocked = false;

void Start() { bt = GetComponent<Button>(); }

// Called when the cursor is actually being locked

void DidLockCursor() { Debug.Log("Locking cursor");

// Disable the button bt.enabled = false; }

// Called when the cursor is being unlocked // or by a script calling Screen.lockCursor = false; void DidUnlockCursor() { Debug.Log("Unlocking cursor");

// Show the button again bt.enabled = true; }

void OnMouseDown() { // Lock the cursor Screen.lockCursor = true; }

void Update() { // In standalone player we have to provide our own key // input for unlocking the cursor if (Input.GetKeyDown("escape")) Screen.lockCursor = false;

// Did we lose cursor locking? // eg. because the user pressed escape // or because they switched to another application // or because some script set Screen.lockCursor = false; if (!Screen.lockCursor &amp;&amp; wasLocked) { wasLocked = false; DidUnlockCursor(); } // Did we gain cursor locking? else if (Screen.lockCursor &amp;&amp; !wasLocked) { wasLocked = true; DidLockCursor(); } } }