question on scripting - variables vs accessing things more directly

Given the following code, is one preferable to the other, and if so, can you explain why?

this one:

private void MyFunction()
{
    Scene currentScene = SceneManager.GetActiveScene();
    string sceneName = currentScene.name;
  
    if (sceneName == "This") { do stuff } ;
}

vs. this one:

private void MyFunction()
{
      
    if (SceneManager.GetActiveScene().name == "This") { do stuff } ;
}

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.

3 Likes

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.

Thank you for the replies! I just wanted to make sure I wasn’t missing something.