Challenge differently

hey. i did the challenge a bit differently and its working, my code is shorter and looks cleaner i think.
my code is:

{
public void OnAnswereSelected(int index)

{

    if (index==question.GetCorrectAnswerIndex())

    {

        questionText.text = "Correct";

        Image buttonImage = answerButtons[correctAnsverIndex].GetComponent<Image>();

        buttonImage.sprite = correctAnswareSprite;

    }

    else

    {

        **questionText.text = "wrong, the correct answer was\n"+ question.GetAnswer(correctAnsverIndex);**

        Image buttonImage = answerButtons[correctAnsverIndex].GetComponent<Image>();

        buttonImage.sprite = correctAnswareSprite;



    }

}

instead of in the video where he is using a variable to get the correctanswer string.

is there any drawbacks doing it this way?

Hi Adrian,

Welcome to our community, and good job on challenging yourself! :slight_smile:

How you are organising your code is mainly up to you and often a matter of personal preference. Generally, readability is very important because, as a game developer, you don’t want to read long lines of code or complex lines of code as they are fairly exhausting to read. To increase the readability of his code, Gary declared a local string variable. Instead of one long line with a string and a method call (which your future self or your team members will probably have to decipher first), he used a self-explanatory variable name: correctAnswer. No guessing needed.

If you have to read question.GetAnswer(correctAnsverIndex) one day, you’ll probably wonder what that method is supposed to return, which is not so great because without knowing what the expected value is, you do not know if the method does return the expected one.

Did this make sense?


See also:

yes i understand! good point. easier to debug to cuz its more understandable too. so what u are saying is always make the as close to a normal sentence that u can? make variables that make sense in its setting even if that means writing a bit longer code.

Yes, that’s basically the goal. Of course, you must find a good balance between readability and the length of the code. I found this comic a while ago which sums the idea up:

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

Privacy & Terms