- Home /
Question by
seemanshudev · Jun 22, 2020 at 10:13 AM ·
gameobjectchildrenaccessing
if i have instantiated gameobjects under a parent object and then after instantiating i need to despawn some of these children randomly how can I achieve that .
if I have instantiated gameobjects under a parent object and then after instantiating i need to despawn some of these children randomly how can I achieve that .
Comment
you can get all children, add to a list and then randomly pick some and then destroy or disable them.
Answer by FeedMyKids1 · Jun 22, 2020 at 02:11 PM
class Spawner : Monobehaviour
{
Transform parent;
List<Transform> children = new List<Transform>();
void DestroyKids( int amount)
{
if (children.Count == 0)
return;
if (amount > children.Count)
amount = children.Count;
for (int i =0; i < amount; ++i)
{
Transform randomChildToSacrifice = children [Random.Range (0, children.Count)];
children.Remove(randomChildToSacrifice);
Destroy (randomChildToSacrifice.gameObject);
}
}
}
it kind of works but it doesn't work on the parent object whose childs I am instantiating through another scripts.
Answer by Rakowu · Jun 23, 2020 at 09:24 AM
have you tried list.Add(GetComponentsInChildren())? Can't try it out here but you need the parent make know the reference. You can find it by tag, find children etc.