-2

I'm really new to coding and I want a 50% chance of raising an int value by 1.

Here's what I'm working with:

public class IfExperiment : MonoBehaviour
{
   [Range(0,100)] public int force = 0;


    // Start is called before the first frame update
    void Start()
    {
        force += 2;
        
    }
    
    

    // Update is called once per frame
    void Update()
    {
        Rigidbody rb= GetComponent<Rigidbody>();

        rb.AddForce(Vector3.one * force);

        

        if (force > 1)
        {
            
            rb.AddForce(Vector3.forward * force);
            

        }
        
    }
}

it's going to speed up the force depending on 'force' int I declared, so I want a chance of raising the value to speed it up.

I tried a lot of different idea on what could be the solution, but I'm just starting to learn C# so I need some help.

Soheil
  • 190
  • 1
  • 1
  • 14

2 Answers2

0

You can use Random class in such a way:

            Random random = new();
            // pass the random instance to your class or method 
            // and work with it afterwards:

            int randomInt = random.Next(0, 2);

            if (randomInt == 0)
            {
                // your int value++
            }
            else
            {
                // something else
            }

The point is, the upper bound is exclusive, so you always get 0 or 1 (not 0, 1 and 2), so it is 50% chance.

Also, make sure to create a single instance of Random class

Random random = new();

And then pass it to your custom class or method, do not create each time new instances of Random class in a loop

Humble Newbie
  • 98
  • 1
  • 11
  • 1
    Beware that the `Random` class can yield repeated values if created every time. [Please see this](https://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values). – Guilherme Mar 13 '23 at 16:28
  • @Guilherme but the user may create only one instance of random and then pass it to the class and use it, no need to create new instance of random each time. Am I right? I've updated the answer, thank you (I knew it, but you are right - it is an important note) – Humble Newbie Mar 13 '23 at 17:52
0

I highly recommend checking out the Scripting API. You can use the UnityEngine.Random.Range for that.

lulasz
  • 1
  • 3
  • Add a little more detail to the answer and if you can, add an example and a piece of code so that the audience can understand better. Thank you. – KiynL Mar 17 '23 at 18:19