- Home /
how get inactive game objects and get their script component and set the variable of script component
but not advise find by tag or somelike layer...
because my game will have town hall and it spawn army and will set their layer and also set the layer of opponent in script to cast sphere
all objects are in inactive pool and have been iinstantiated
Answer by yummy81 · May 01, 2020 at 06:10 PM
You can put into the array all the inactive gameobjects like this:
GameObject[] g = SceneManager.GetActiveScene().GetRootGameObjects().Where(e=>!e.activeSelf).ToArray();
Then, you can simply iterate through all the elements in the array, grab the script component you want, and change the public variables:
for (int i = 0; i < g.Length; i++){
var script = g[i].GetComponent<YourScript>();
if (script!=null){
script.YourScriptPublicVariable = YourValue;
}
}
Remember to add required namespaces:
using System.Linq;
using UnityEngine.SceneManagement;
Answer by sath · May 01, 2020 at 06:12 PM
If you know their parent you can do
YourScript[] allScripts = parent.GetComponentsInChildren<YourScipt>(true);
where true means include inactive.
Update: added a test scene
no... i want something like getcomponents in children... but that is not going below level 5 children... cannot use all objects... player and enemy have the same script but need to set layerofopponent different through code
i have tried...i am searching from the parent object...but it is not giving me the last children list..just giving second last list of the objects... and last children are on 7th level of hierarchy.. is there any limit of getcomponentinchildren///
I am sorry but without your code I can only imagine what you are trying to do. If your child is on 7th level you should iterate GetComponentsInChildren for each child and if you know the name or the script it is better because you can exit the loop sooner with break;
Your answer
![](https://koobas.hobune.stream/wayback/20220612233010im_/https://answers.unity.com/themes/thub/images/avi.jpg)