- Home /
Showing and locking the cursor at right time.
Hi!
I am new at programming and I have a problem with showing and locking the cursor when I want. Now my cursor in menu isn't showing at all but it works fine in pause screen and in the game.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CursorLock : MonoBehaviour
{
Scene currentScene;
string sceneName;
// Start is called before the first frame update
void Start()
{
// Create a temporary reference to the current scene.
currentScene = SceneManager.GetActiveScene();
// Retrieve the name of this scene.
string sceneName = currentScene.name;
}
private void Update()
{
if (sceneName == "Main Menu" || PauseMenu.GameIsPaused == true)
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
else
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
}
I would greatly appreciate if you could help me :).
Sorry for my bad English.
Answer by CorruptedTNC · Sep 29, 2020 at 05:19 PM
When you retrieve the name of the scene, you're creating a new local variable with the same name as your private field sceneName
. So your field sceneName
is going to remain as null (default value for a string).
Instead of string sceneName = currentScene.name
, sceneName = currentScene.name
would give you the result you want.
A better solution to this would be to tell Unity not to destroy your script on load using DontDestroyOnLoad and instead hook the sceneLoaded event to get the scene name and enable/disable the cursor when loading.
Then, your pause script can turn the cursor on/off depending on current scene when a button is pressed, instead of constantly checking the scene in the update loop.
Thank you so much for the answer! I'll definitely try this. :)
Your answer
Follow this Question
Related Questions
Controlling the mouse in an FPSController 0 Answers
Cursor.LockState = CursorLockMode.Locked doesn‘t works。 0 Answers
Cursor not getting centered 0 Answers
UI Question 1 Answer
cursor visible not working please help 0 Answers