[C#] Random.Range keeps picking the same number
Hi, Im making a simple game, Pong. I'm using Random.Range to choose from 0 and 1 to determine which side the ball will go. I notice it keeps going left. There should be a 50/50 chance of it going right or left, but it keeps going left. I even used the Print function on my random.range variable to see what is going on. It just keeps picking 0 over and over again, making the ball go left. I don't know what is going on.
Here is my code: private Rigidbody2D rbBall; private Vector2 Ballmovement;
     void BallStart()
     {
         int direction = Random.Range (0, 1); //choose 0 or 1 for x axis (left or right)
         print (direction);
         if (direction == 0) { //if its 0... 
             int dirLeft = Random.Range (1, 2); //then choose again for y axis (up or down)
             if (dirLeft == 0 { // if it chooses 0 again...
                 Ballmovement = new Vector2 (-0.15f, 0.05f); //then the ball goes left and up
             } else {
                 Ballmovement = new Vector2 (-0.15f, -0.05f);//otherwise, it goes left and down
             }
         } else { //same thing for the right side
             int dirRight = Random.Range (1, 2);
             if (dirRight == 1) {
                 Ballmovement = new Vector2 (1.5f, .5f); // right, up
             } else {
                 Ballmovement = new Vector2 (1.5f, -.5f);// right, down
             }
         }
     }
 
     void Start()
     {
         rbBall = GetComponent<Rigidbody2D> ();
         BallStart();
     } // fixed update and rbBall.addforce comes after this, I didn't include it in the script here.
Hope you can help. Thanks for viewing!
Answer by UnityCoach · Mar 31, 2017 at 12:42 AM
The max for the int version of Random.Range() is exclusive. You want to use Random.Range (0, 2). 
Answer by GamingOink · Mar 31, 2017 at 05:56 AM
Random.Range has two parameters, a minimum number and a maximum number like this: Random.Range(min, max). But the maximum number is not inclusive when the random integer is picked between the range of numbers you want. An example is:
 int rand = Random.Range(0, 4);
In this code a random number will be picked between 0 and 3. The number 4 is excluded. What you want is:
 int direction = Random.Range (0, 2); //choose 0 or 1 for x axis (left or right)
Hope this helps. Cheers mate!
Your answer
 
 
             Follow this Question
Related Questions
I guys I have a really hard question 0 Answers
How to add a editing option to variables in a script in Inspector? 0 Answers
How to create buttons with script? 0 Answers
Side-scrolling Enemy AI not shooting in the right direction 0 Answers
How to make a random object generator that responds to simple touch? 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                