I am currently doing an tutorial from an e-book and found such a case where putting
var halfW outside Update() gives a little bit different results than having it inside Update().

The code moves a box with a mouse on x axis.

Having var halfW : float = (Screen.width/2); outside Update() function, the transform.position.x is 10x larger on the right side as when having the halfW in the Update(). Everyhting works when I move my mouse to the left side.

So my question is: Why is it working for the left side but differs 10x on the right side?

I’ve done some reasearch but nothing definitive has risen. I do suspect there is something to do with event ordering but no documentation tells me exactly when Screen gets its info. For future reference, where I could get this knowledge at what times certain classes/variables get there values? and then perhaps where to declare them? (This is where I originally read from: Execution order)

Also read that Screen might take active windows’s size into account. (Reference) I do use editor view but with “Maximize on play” and width is the same as my resolution’s width.

Would like to get some clarifications on such topic.

Here is the JS code for Unity 3D 3.5:

#pragma strict
    
var halfW : float = (Screen.width/2); //Having it outside gives 10 when going right.

function Update () {
 //var halfW : float = Screen.width/2; //Gives the needed result

 transform.position.x = (Input.mousePosition.x - halfW)/halfW;
 Debug.Log((Input.mousePosition.x - halfW) / halfW);
}

Probably this has something similar to do?

You shouldn’t put code outside functions. Only declare variables outside functions; actual code should always be inside a function. Otherwise the screen width is coming from the editor, possibly the scene view, and only once, when the script is attached to an object, after which it’s serialized. In this case you can do

var halfW : float;

function Start () {
    halfW = Screen.width/2;
}