Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

question on scripting - variables vs accessing things more directly

Discussion in 'Scripting' started by stain2319, Apr 1, 2021.

  1. stain2319

    stain2319

    Joined:
    Mar 2, 2020
    Posts:
    418
    Given the following code, is one preferable to the other, and if so, can you explain why?

    this one:

    Code (CSharp):
    1. private void MyFunction()
    2. {
    3.     Scene currentScene = SceneManager.GetActiveScene();
    4.     string sceneName = currentScene.name;
    5.  
    6.     if (sceneName == "This") { do stuff } ;
    7. }

    vs. this one:

    Code (CSharp):
    1. private void MyFunction()
    2. {
    3.      
    4.     if (SceneManager.GetActiveScene().name == "This") { do stuff } ;
    5. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    Performance-wise there is no difference between the two; the CPU needs to grab and store all these things the same way regardless.

    The first one is better for debugging and for code readability. For example, if you get a NullReferenceException on line 4 in the top code then you know for sure that currentScene is null. If you get the same NullReferenceException on line 4 of the bottom code, you have a LOT more bits that could possibly be null.
     
    Vryken, Sphinks and PraetorBlue like this.
  3. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    If you are going to use "currentScene" again in the function, you better use the first one.
    I suggest using the first way in order to make the code more readable.
     
  4. stain2319

    stain2319

    Joined:
    Mar 2, 2020
    Posts:
    418
    Thank you for the replies! I just wanted to make sure I wasn't missing something.