Cursor.lockState does not work

simply coded:

void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

And there is nomore code changing the Cursor.lockState.

It works fine except when I’m using window mode, switching out with Alt+Tab. Then the mouse will not be locked at all, even after switching back and clicking inside the window many times.

I’ve tried development build, normal build and in-editor run, all of them have the same issue.

Unity version is 2018.1.6f1.

It’s not a perfect solution but if I understand your problem this might help.
When Alt+Tabing in the window and clicking with the mouse it should lock itself again.

(Input.GetMouseButtonDown (0)) 
{
     Cursor.lockState = CursorLockedMode.Locked;
}

I am new to Unity too but I hope I could help

Put it on the awake method