- Home /
How can I change cursor visibility and cursor lock state when I press tab then revert it back when I press tab again.
In my game I have an inventory system toggle-able by tab. What I also want to happen when I press tab is for the cursor to become visible and movable so I can move items around my inventory with out pressing escape then when I press tab I want the cursor to be locked and invisible just like it started.
Answer by HammerCar · Sep 10, 2017 at 08:05 PM
What you are looking for is Cursor.lockState and Cursor.visible.
https://docs.unity3d.com/ScriptReference/Cursor-lockState.html https://docs.unity3d.com/ScriptReference/Cursor-visible.html
void OpenInventory ()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
void CloseInventory ()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
And pressing escape to see the cursor only works in the editor not in a build.
So using you answer up above I tried to write a script but when I get into the game and press TAB my inventory opens, I see the cursor, but then it disappears. $$anonymous$$y script is on my main camera. Also if it helps I tried it in both build mode and in unity.
I will include my script below
using UnityEngine;
using System.Collections;
public class cursorScript : $$anonymous$$onoBehaviour
{
private bool inventoryIsOpen;
void Start()
{
inventoryIsOpen = false;
}
void Update()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Tab))
{
if(inventoryIsOpen == false)
{
OpenInventory();
}else if(inventoryIsOpen == true)
{
CloseInventory();
}
}
}
void OpenInventory()
{
Cursor.lockState = CursorLock$$anonymous$$ode.None;
Cursor.visible = true;
inventoryIsOpen = true;
}
void CloseInventory()
{
Cursor.lockState = CursorLock$$anonymous$$ode.Locked;
Cursor.visible = false;
inventoryIsOpen = false;
}
}
I tested the code you gave me and it worked as intended. If you mean that the cursor disappears right after you see it you might have something setting Cursor.visible to false.
Okay thanks for your time. I deter$$anonymous$$ed that it was a setting on the first person prefab (which I was using) to lock the camera now the script works fine. Again thank you for your time.
Your answer
Follow this Question
Related Questions
Trouble with unlocking cursor 1 Answer
Cursor.LockState = CursorLockMode.Locked doasnt works. 0 Answers
Lock cursor on current position 2 Answers
Issues with mouse input when locking the cursor 0 Answers
Cursor locking and visibility. 0 Answers