When does the screen size get set in Unity Editor?

The following code:

void Start()
{
    Debug.Log("SWIDTH: " + Screen.width);
    Debug.Log("SHEIGHT: " + Screen.height);
}

void Update()
{
    Debug.Log("SWIDTH: " + Screen.width);
    Debug.Log("SHEIGHT: " + Screen.height);
}

Produces the following:

SWIDTH: 640
SHEIGHT: 480
SWIDTH: 640
SHEIGHT: 480
SWIDTH: 640
SHEIGHT: 480
SWIDTH: 900
SHEIGHT: 600
SWIDTH: 900
SHEIGHT: 600
SWIDTH: 900
SHEIGHT: 600
SWIDTH: 900
SHEIGHT: 600
etc etc

I want to use Screen.Width and Screen.Height for calculations in initialisation. However both of these are wrong in Start and for the first couple of frames of Update. So I’m just wondering when exactly do these screen variables get set? Does the delay in updating these variables only occur in the Unity Editor, or does it do this in builds as well?

According to what I’ve read on these forums at least, this is a bug in the current version of Unity.

This is a known issue and it only happens in the editor (it is a problem with switching from the scene view to the play view - this doesn’t happen in the built project).

You could turn Start() into an IEnumerator and just have a yielding while loop that waits for a change in width/height, ie:

float sheight;
    float swidth;

    IEnumerator Start()
    {
        sheight = Screen.height;
        swidth = Screen.width;

        while (sheight == Screen.height  Time.timeSinceLevelLoad < 5)
        {
            yield return null;
        }

        while (swidth == Screen.width  Time.timeSinceLevelLoad < 5)
        {
            yield return null;
        }

        sheight = Screen.height;
        swidth = Screen.width;
    }

aah sorry Andeee only just saw your post, though you could make my code editor specific! :stuck_out_tongue:

ah ok thanks guys. At least i know that builds will not have this problem :slight_smile:

to make the code only being present in the editor enclose it with

#if UNITY_EDITOR
… your code
#endif