control over the possibility of a Random.Range function from an array's elements

(I'm really sorry if the title is a mess, I can't put it simply in a few words)

I have a built-in Array, "myArray". Right now, I use this:

randomArrayElement = Random.Range (0,myArray.length);

to pick a random element from myArray. What I want is to increase the possibility of certain elements to be picked by this function.

Till now I've been doing it by inserting them more than once from within the editor (so the array has one instance of each element and say 5 instances of a certain element that I want to have randomly picked more frequently).

Is there a code-based way to do this? Thanks :)

Hi schwertfish,

You can do something like this in C#

Basically create a for loop, that runs 5 times, in each iteration, if the first element is returned, you break out of the for loop, if not the loop will try another 4 times to try and return the first element, else it will return another element. You can adjust the values of course to determine how often, and which element you would prefer to get out.

for(int i = 0; i < 5; i++)
{
  randomArrayElement = Random.Range(0,5);

  // If the first element (which is the preferred element is chosen), exit the loop
  if(randomArrayElement == 0)
    break;
}

Or if you want multiple elements to be favoured, such as the 2nd and 4th element..

for(int i = 0; i < 5; i++)
{
  randomArrayElement = Random.Range(0,5);

  // If the preferred 2nd or 4th elements are chosen, exit the loop
  if(randomArrayElement == 1 || randomArrayElement == 3)
    break;
}