Hi! I am new to unity, and in my game I have a player that can rotate, walk, and jump. When the game is running, the cursor is locked to the center of the screen and the cursor is hidden. I have a menu that opens when I hit the escape key, and that shows my cursor and unlocks it, but when I try to click on any buttons, the cursor hides and goes back to the center of the screen, and if I tap escape without clicking any buttons, the cursor is still shown and not locked to the middle of the screen. Also while the Menu is up, the player is still able to move and rotate, which I do not want. Can anyone help me?
My code:
Code for the Third Person Camera Controller (rotation and camera following):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonCameraController : MonoBehaviour
{
public float RotationSpeed = 1;
public Transform Target, Player;
float mouseX, mouseY;
bool CursorLockedVar;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
CursorLockedVar = (true);
Cursor.visible = false;
}
public float smoothSpeed = 0.125f;
private void LateUpdate()
{
CamControl();
}
void CamControl()
{
mouseX += Input.GetAxis("Mouse X") * RotationSpeed;
mouseY -= Input.GetAxis("Mouse Y") * RotationSpeed;
mouseY = Mathf.Clamp(mouseY, -35, 60);
transform.LookAt(Target);
Target.rotation = Quaternion.Euler(mouseY, mouseX, 0);
Player.rotation = Quaternion.Euler(0, mouseX, 0);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape) && !CursorLockedVar)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = (false);
CursorLockedVar = (true);
}
else if (Input.GetKeyDown(KeyCode.Escape) && CursorLockedVar)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = (true);
CursorLockedVar = (false);
}
}
}
Code for my Character controller (movement)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonCharacterController : MonoBehaviour
{
private CharacterController controller;
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 8.0f;
public float Speed;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
PlayerMovement();
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = new Vector3(0, verticalVelocity, 0);
controller.Move(moveVector * Time.deltaTime);
}
void PlayerMovement()
{
Vector3 moveVector = Vector3.zero;
float ver = moveVector.z = Input.GetAxis("Vertical") * 5.0f;
float hor = moveVector.x = Input.GetAxis("Horizontal") * 5.0f;
Vector3 playerMovement = new Vector3(hor, 0f, ver) * Speed * Time.deltaTime;
moveVector.y = verticalVelocity;
controller.Move(moveVector * Time.deltaTime);
transform.Translate(playerMovement, Space.Self);
}
Thank you for your time, and have a good day!