- Home /
Deactivate the children
So this script will randomly deactivate game objects once the level starts. The only problem is that it doesn't deactivate the children of these game objects. Can someone modify this for me please. Thanks.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomEnabledOnStart : MonoBehaviour {
public List<GameObject> itemsForRandomEnable=new List<GameObject>();
void Start () {
if (itemsForRandomEnable!=null && itemsForRandomEnable.Count>0)
{
int itemId=new System.Random().Next(itemsForRandomEnable.Count);
for (int i=0; i<itemsForRandomEnable.Count;i++)
{
if (i==itemId){itemsForRandomEnable[i].gameObject.active=true;}
else{itemsForRandomEnable[i].gameObject.active=false;}
}
}
}
}
Answer by Tim-Michels · Nov 26, 2012 at 12:45 PM
There's a function called SetActiveRecursively which has effect on all the children of that object.
In your case you should do something like this:
itemsForRandomEnable[i].gameObject.SetActiveRecursively(false);
Please mark as answered if this helped you.
Cheers ;)
Answer by Kryptos · Nov 26, 2012 at 01:12 PM
GameObject.SetActiveRecursively and GameObject.active are deprecated in Unity 4.x.
You need to use GameObject.SetActive or GameObject.activeSelf or GameObject.activeInHierarchy.
Really? Well, thanks for the info. I haven't stepped into Unity 4 at this time since I've heard some issues upon upgrading and I need to finish my project this December. I'm currently using 3.5
Your answer
Follow this Question
Related Questions
Randomly deactivate game objects 2 Answers
How to activate and deactivate a gameObject 1 Answer
How to set up random spawnpoints? 1 Answer
Random movement on a plain 2 Answers