Question regarding writing good code

I see that he often likes to store things like GetComponent in variables and then using those variables, instead of just using GetComponent by itself. For example his SetDefaultButtonSprites() has these two lines:
Image buttonImage = answerButtons[i].GetComponent();
buttonImage.sprite = defaultAnswerSprite;

However i feel that there is no need to make the buttonImage variable since the scope is just that for loop, and is very simple. So i wrote this instead:
answerButtons[i].GetComponent().sprite = defaultAnswerSprite;

Could this way of writing code be worse or more confusing for some in some way?

The same way of writing could also be applied to the whole of:
Image buttonImage;

correctAnswerIndex = question.GetCorrectAnswerIndex();
string correctAnswer = question.GetAnswer(correctAnswerIndex);
questionText.text = “sorry, the correct answer was;\n” + correctAnswer;
buttonImage = answerButtons[correctAnswerIndex].GetComponent();
buttonImage.sprite = correctAnswerSprite;

but i feel like not creating the buttonImage, correctAnswerIndex, and correctAnswer variables in that situation could make it a bit too confusing.

It all depends. On simple examples like this, it’s more than fine.

When you start getting to a point where you you’ve added a bit of complexity and/or need to debug problems that crop up, you’ll appreciate a more laid out approach.

2 Likes

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

Privacy & Terms