Beginning C# - Part 8: Conditionals | Ray Wenderlich

In this episode, you'll learn how to make choices based on your data through the use of conditionals, otherwise known as if statements.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3247-beginning-c/lessons/8

Just wanted to say this entire series is really awesome. As someone brand new to Unity and C# from game maker, this tutorial is making C# much more approachable and making me feel like I actually will be able to understand it. Thank you for creating such a great piece of content and most of all allowing me to access it for free.

PlayerGold would have to be 1001 to buy the sword, instead of 1000. By the way I this series is excellent.

Sir, I watched your whole video. In the last when you were giving us the challenge to make a Game to Guess the Number, you showed us the code for generating the random numbers. That code has some mistake.

Corrected code is:
int randomNumber;
void OnEnable(){
randomNumber = Random.Range(1,10);
}

The code on the slide is correct. OnEnable will run everytime the script is enabled or disabled whereas Start() will run only once. You don’t want to change the random number everytime the user guesses as it would be a frustrating user experience.

Regarding the Challenge: I was unable to generate a random integer between 1 and 9 (if I am not mistaking the 1 is included where as the 10 is not making 9 the highest possible number that could be generated) using:

int randomNumber;
void Start()
{
randomNumber = Random.Range(1, 10);
}

Rather than generating random number between 1 and 10, this code would only generate 0 for me every time I ran it in Unity. As far as I was concerned 0 was not even the range of numbers I had set to begin with. I had decided to print out the random number every time I disabled the cube to check if my conditionals were working and while the conditionals check out, I found that the code would only produce 0 every time I clicked the start/play in Unity. To work around this I initialized randomNumber as a float and then cast it back down to an integer upon assigning it the random value between 1 and 9, like so:

float randomNumber;

void Start()
{
    randomNumber = (int) Random.Range(1, 10);
}

While this seems to have worked quite flawlessly for my purposes I am still a little concerned I was missing something when trying to produce a random integer and would like to know if you any ideas on why I was only getting 0 back before I initialized randomNumber as a float. I apologize for the novel, but am quite intent on learning thoroughly, very much appreciate the free videos and and think their a great tool for beginners like me. Thanks for your time and advice you have to offer.

cheatcode :smiley:
Debug.Log(randomNumber);
thanks for the great series :slight_smile:

@deprogrammer Thank you for sharing this - much appreciated!

1 Like

@oussouss Glad you like it! Cheers! :]

1 Like