Quiz Master - temporary variable

I’m doing the Unity 2D course and have been slowly working through the Quiz Master project. I’ve found it harder to get my head around the content of this project than the first two, and feel like things that could use a little extra explanation instead are just introduced and ignored.

Case in point, from lecture 58/59:

TextMeshProUGUI buttonText = answerButtons[i].GetComponentInChildren();
buttonText.text = question.GetAnswer(i);

During the lecture we are told that we are going to introduce a temporary variable, but this is not a term that has come up before in the course and it doesn’t get an explanation. My vague understanding is that in order to link to complicated pieces of code, you make one simpler piece of code that in itself doesn’t belong in the Inspector or Hierarchy, but is a link to something that is. Is that about right?
I’m curious if this code could have worked without using the temporary variable - i.e. just making it so that the text component in the answerButtons game object = question.GetAnswer(i).

Hi SpecialJstorm,

Yes, you are right. All variables declared in methods are temporary because they get destroyed after the method finished executing its code. These variables are also called local variables because they exist in the local scope of the method only. The opposite would be an instance variable, which exists during the lifetime of the instance/object of the class. And there are also static variables, which belong to the class. They exist as long as your program is running.

In most cases, we create local variables to make our code more readable. The two lines in your post would look like this without the temporary variable:
answerButtons[i].GetComponentInChildren().text = question.GetAnswer(i);

That one-liner is quite difficult to read and understand, isn’t it? Of course, we could decipher it but we usually don’t want to waste our time doing that.

Feel free to rewrite the code to explore your ideas and to improve your own coding skills. The compiler will complain if the code is invalid.

Did this help?


See also:

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

Privacy & Terms