- Home /
How to use a foreach loop to disable scripts on objects within a GameObject array?
I have a script that gets all objects in the scene with the tag 'villager' and stores them in a GameObject array. i want to loop over these objects and disable a script that is stored on each of them, how would i go about doing this?
private void Awake()
{
selectedUnitRTSList = new List<UnitTargeter>();
selectionAreaTransform.gameObject.SetActive(false);
GameObject[] villagers = GameObject.FindGameObjectsWithTag("Villager");
Debug.Log(villagers.Length);
foreach (GameObject obj in villagers)
{
}
Cheers in advance
Answer by Klarzahs · Oct 06, 2020 at 03:45 PM
Hi @WookieMilk
if you want to disable a script, you can use the obj.GetComponent<SCRIPTNAME>()
function. This returns an object which you can then deactivate by using SetActive(false)
.
You can find additional information here
SetActive is a method of the GameObject class and deactivates the whole gameobject. To enable / disable a component you set it's enabled property to false. So if he just want's to disable a certain script component on all of the objects he can just do
foreach (GameObject obj in villagers)
{
obj.GetComponent<YourComponent>().enabled = false;
}
Argh, you are of course right, i always mix those two up. Thanks for the clarification