Code Explained: ButtonCheckScore - Task 1 Part 2

This code checks the score inputted in the text field and displays the colour of the medal that the user would have won depending on the score. 

This is an explanation of the code used for this task:

The public variables m_colours as the type 'colour', m_inputfield as the type 'input field', m_medalImage as the type 'image', m_mediaText as the type 'text' are declared.

The function GetScoreandSetMedal() has no parameters and uses a try catch statement which are used to handle exceptions. The integer variable 'value' is declared. The try block is where exceptions occur and therefore handles what happens when an unvalid input such as a letter is inputted into the text field. The try block uses int.parse to convert the text string inputted into the input field into an integer which is set in the integer variable 'value'. However if a random letter is inputted instead, then the statement catches this exception and therefore sets the value in the integer variable 'value' to zero. Therefore this means that the scene will be set to 'bronze' as the value set to the variable 'score' is less than the value set to the variable 'silver'.

The variable 'value' is then passed by parameter to the function SetMedal(int score) and sets the value stored in the variable 'value' in the integer variable 'score' declared in the functions parenthesis. This variable can then be used within this function as the value has been passed locally - this avoids setting the variable 'score' to a global variable. 

In the function SetMedal(int score), the integer variables 'silver' and 'gold' have been declared. The integer assigned to the variable 'silver' is 10, while the integer assigned to the variable 'gold' is 15. This function uses an if statement that states that if the value stored in the variable 'score' is less than the value stored in the variable 'silver' then the scene would be set to bronze and the media image colour would be set to the first colour set in the variable 'm_colours' array in the visual part of unity.

Otherwise if the value stored in the variable 'score' is less than or equal to the value stored in the variable 'silver' and the value stored in the variable 'score' is less than the value stored in the variable 'gold' then the scene is set to silver and the media image colour would be set to the second colour set in the variable 'm_colours' array in the visual part of unity.

The else part of the if statement sets the scene to gold as the value set in the variable 'score' is either the same value or higher than the value stored in the variable 'gold'. The media image colour is set to the third colour set in the variable 'm_colours' array in the visual part of unity.



Comments

Popular posts from this blog

Unity Project 4: Ball platformer game

[Research] Traditional Poster Design (4CTA1214)