1

I want to randomly assign 0 or 1 to randomNumber1, but I failed with this code.

This is the code in Unity

public class Practice : MonoBehaviour
{

    public static int randomNumber1;   
    public static int randomNumber2;

    public class randd
    {
        public void randdom_dd()
        {
            int randomNumber1 = Random.Range(0, 2);
            if (randomNumber1 == 0)
            {
                int randomNumber2 = 1;
            }

            else
            {
                int randomNumber2 = 0;
            }
        }

    }

    public void OnClick()
    {
        if (randomNumber1 == 0)
        {
            print("정답!");   
        }

        else
        {
            print("틀렸어!");
        }

    }
}

I think, when I play the codes, randomNumber1 has always same int. I've tried to change the min and max in Random.Range(min, max) and some tries, I failed.

MX D
  • 2,453
  • 4
  • 35
  • 47
Yong C
  • 41
  • 3
  • I'm not sure why you need 2 variables? I think you'd be able to get the same functionality, but less complication, out of just using randomNumber1 and checking the value of it in the if/else statements. The upper bound for Random.Range is exclusive, meaning for Range(0,2) only 0 or 1 will ever be returned, which is what you want. – Catlover Jun 21 '19 at 15:00
  • You don't seem to be triggering `randdom_dd()` anywhere. Try adding it to the OnClick function before you do the IF – MX D Jun 21 '19 at 15:12

2 Answers2

1

It looks like your random_dd method isn't actually being called anywhere. Because randomNumber1 is defined as a field, it will automatically instantiate to zero. This is why you are always seeing your random number show up with the same value.

Try calling the random_dd method before the OnClick method is being hit, or just calling the random_dd method at the top of your OnClick method before you evaluate your random variable, and see if that works. Here's a link to an example that elaborates on the definitions of fields in C# Defining a Field in C#.

You also shouldn't be using the 'int' keyword when assigning a value to variables that have already been defined in your program, which in your case are the randomNumber1 and randomNumber2 variables.

Luke
  • 838
  • 7
  • 17
1

thanks all of you! it works with this codes and yes, you are right, jmrpink. i don't use randomNumber2 in this code. my mistake!

public void OnClick()
{
        int randomNumber1 = Random.Range(0, 2);
        if (randomNumber1 == 0)
        {
            int randomNumber2 = 1;
        }

        else
        {
            int randomNumber2 = 0;
        }
    if (randomNumber1 == 0)
    {
        print("정답!");   
    }
    else
    {
        print("틀렸어!");
    }

}
Yong C
  • 41
  • 3