Search Unity

Is there hidden performance cost for calling Screen.height or width?

Discussion in 'Scripting' started by AhSai, Apr 25, 2019.

  1. AhSai

    AhSai

    Joined:
    Jun 25, 2017
    Posts:
    129
    Hi, I am just wondering if there is any extra performance cost for calling Screen.height or width on every frame? (Just like Time.deltaTime that is more than just reading a static int.)
     
  2. N_Murray

    N_Murray

    Joined:
    Apr 1, 2015
    Posts:
    98
    Sorry this isn't an answer but I'm just curious as to why you need to call it every frame? Surely your screen size can't be changing that often?
     
  3. AhSai

    AhSai

    Joined:
    Jun 25, 2017
    Posts:
    129
    It is because I have multiple scripts that do stuffs in proportion to the screen size. If there is no added performance cost to Screen call, it will be more convenient to get size directly from Screen class then caching it and changing it every time resolution is changed.
     
  4. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    It has a cost of native method call.

    Managed wrapper does basically this:
    Code (CSharp):
    1.     /// <summary>
    2.     ///   <para>The current width of the screen window in pixels (Read Only).</para>
    3.     /// </summary>
    4.     public static extern int width { [NativeMethod(IsThreadSafe = true, Name = "GetWidth"), MethodImpl(MethodImplOptions.InternalCall)] get; }
    5.  
    6.     /// <summary>
    7.     ///   <para>The current height of the screen window in pixels (Read Only).</para>
    8.     /// </summary>
    9.     public static extern int height { [NativeMethod(IsThreadSafe = true, Name = "GetHeight"), MethodImpl(MethodImplOptions.InternalCall)] get; }
    In my experience the cost in calling this every frame (in one instance) is near to not existant.

    If you need multiple scripts to access it, gather width / height from one instance and then dispatch changes via event or stream.
     
    Natzke likes this.