Please anybody can help me on probability of child Game objects
I want this type of snareo
child (0) = 20% chance,
child (1) = 30% chance,
child (2) = 10% chance,
child (3) = 40% chance,
I am using this code
timer += Time.deltaTime;
if(timer>crate_timer)
{
int rndm = Random.Range(0,6); // here I want probablity not randomness
for (int i=0; i<transform.childCount; i++)
{
transform.GetChild(rndm).gameObject.SetActive(true);
}
timer = 0;
}
The way I handle this is to create a temporary list containing multiples of the child indices where each entry in the list is worth 1% point (so 100 entries). For instance, if you have two children, and you want the first child to be chosen 75% of the time:
List<int> indices = new List<int>();
// Add the child 0 element 75 times
for (int i=0; i < 75; ++i)
indices.Add(0);
// Add the child 1 element 25 times
for (int i=0; i < 25; ++i)
indices.Add(1);
int ranVal = Random.Range(0, indices.Count);
int childIndex = indices[ranVal];
transform.GetChild(childIndex).gameObject.SetActive(true);
Obviously you would not need to add 100 items in this case, because the ratio is 1 to 3, so you could indeed just add three "0"s and a single “1” into the indices list. Then you’d have 1 in 4 chances to get a 1 and 3 in 4 chances to get a 0 (where 1 and 0 are the index into the child transform array).
If you’re simulating a bag, removing an item (indices.RemoveAt(ranVal)) decreases the chance of getting that item next time, so you could also remove the index from the indices list. So if you pull out a 0, all that is left in the list are 1’s. In this case, you must add the exact number of elements you plan to have in the bag (you can’t use 75 and 25 just because they nicely add to 100%, unless you explicitly have 100 items in the bag).