- Home /
randomly pick a value from a tuple
Hello, i need to pick a value from a tuple (-1.0f, 1.0f)
i could seem like, if exist, may be:
value = Random.someting(tuple(-1.0,1.0)) ....
value assigned with -1.0 or 1.0 for example.
Or is there any other alternative way? Thank you ..
Answer by ModLunar · Nov 26, 2018 at 02:40 PM
I'm not sure if I'm understanding correctly, but say for example, if you have a Vector3, and you wanted to randomly pick one of its xyz components:
You can actually index into Vector3s (along with Vector2s, Vector4s, Vector2Ints, and Vector3Ints) as if they are arrays (thanks to C# indexers!). So for example, you could do this:
using UnityEngine;
//...
Vector3 tuple = new Vector3(12, -15, 18);
//Note:
//tuple[0] is 12
//tuple[1] is -15
//tuple[2] is 18
//Trying to access tuple[3] would throw an IndexOutOfRangeException, since there are only 3 components to a Vector3 and tuple[3] would be the fourth.
//Get a random integer in range [0, 2], meaning 0, 1, or 2. This will be used as an index into the Vector3.
int randomIndex = Random.Range(0, 3);
//result will be either 12, -15, or 18.
float result = tuple[randomIndex];
Doing the same thing, written shorter, you can do:
using UnityEngine;
//...
Vector3 tuple = new Vector3(12, -15, 18);
float result = tuple[Random.Range(0, 3)];
Answer by s_awali · Nov 26, 2018 at 03:00 PM
As Tuple are introduced in C#7.0, and Unity use C#3.5 (or 4.0 in preview), Tuples are not available.
Still, you can use a Vector2 to achieve the same effect. Then, you can use Random.Range(minValue, maxValue);
to randomly pick a value between minValue and maxValue.
/!\ If minValue and maxValue are integers (int), then maxValue is exclusive /!\