This site uses strictly necessary cookies. More Information

X- Home /

# probability of child Game objects

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;
}
```

$$anonymous$$ay I know the solution for this answer? I am having the same problem

**Answer** by supernat
·
Apr 09, 2015 at 04:53 PM

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).

Thankx supernat I figured it out , but that is very good answer. Thankx again

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Trouble with Random.value and Percentage 1 Answer

Multiple Cars not working 1 Answer

Clean way for percentages 0 Answers

Distribute terrain in zones 3 Answers

Spawn chance in my spawner. 2 Answers