Using a variable in LoadNextSceen

Why do we create a variable, currentScene, when it isn’t used. Why do we use this:

int currentScene = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentScene + 1);

over this:

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

Hi Terry,

We did that for the sake of readability. Our currentScene variable represents our idea. If we take a look at this code in a couple of months, we’ll immediately know what the purpose of the next line is: LoadScene loads currentScene.

The one-liner could require some guesswork. GetActiveScene() might make sense but what about buildIndex? Maybe we will have to look that up to understand the code in the future.

I recently found this webcomic which sums the idea up pretty well, in my opinion:

Did this make sense? :slight_smile:


See also:

I understand what you are saying but it don’t make sense because
// that’s what a comment section is for, is it not?

But no worries, I am just trying to understand a little deeper. I can understand using a variable if one is going to use it. When it is included, I would expect it to be used somewhere and would be confused if I couldn’t find it in a “couple of months”. Thanks :slight_smile:

Well, in the end, it’s a matter of personal preference whether you use a variable or not. There is no “right” and “wrong” because everybody has got their own habits. Some people are used to reading one-liners. Others aren’t.

The best would be if you just do what feels right for you now. I can explain a lot all day long but some things can only be learnt by experience. Write your code as you want, and in a couple of weeks or years, when you revise your older code or read other people’s code, you’ll very likely know what you could do to improve the readability for you.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms