- Home /
Return All gameobjects in scene to an array
How might I return all the gameobjects, and their children into an array?
This is so I might loop through and apply a global materials change.
Tagging gameobjects is out of the question unless there is a way to apply a tag to all the children in the gameobject (So i can reference them individually)
Don't you, ins$$anonymous$$d, want FindObjectOfType(Renderer)? Not all of the Game Objects are going to have materials associated with them. Also, that might not even be necessary. What about Shader.SetGlobal...?
how might Shader.SetGlobal... work? It is indeed a global shader change that Im looking to do, but according to the documentation, the only think that might be useful is SetGlobalTexture, but its not the texture I want to change, its the actual shader.
Also I wasnt aware of the FindObjectOfType() function, that might be the answer if the SetGlobal comes up short.
Answer by Peter G · May 08, 2011 at 11:52 PM
Have you tried:
var gameObjs : GameObject[] = FindObjectsOfType(GameObject) as GameObject[];
Thanks, like I mentioned above, I wasnt aware of the FindObjectsofType() function thats probably what I was looking for.
How about if only some objects in the scene but not all gameobjects? Thanks for answering.
Answer by colinday · Dec 02, 2016 at 06:07 PM
Scene scene = SceneManager.GetActiveScene();
GameObject[] rootObjects = scene.GetRootGameObjects();
Answer by beachpong · Mar 14, 2015 at 01:39 AM
Hi,
Let's say you want to access only the gameobjects that you have in your scrpit (e.g script name is DemoScript). To access only these game objects, try this:
object[] obj = GameObject.FindObjectsofType(typeof(DemoScript));
foreach(object o in obj)
{ //do something }
Hope this helps.
Hi! beachpong! $$anonymous$$ay I ask you a question? Your "foreach(object o in obj)",if I want to use for-loop ins$$anonymous$$d of using foreach, how should it be? Thx!
Answer by beachpong · Mar 14, 2015 at 12:11 PM
Hi Tomleung,
Sure. You can try this.
object[] obj = GameObject.FindObjectsofType(typeof(DemoScript));
for(int i=0;i
Why your answer is not completed? Should it be object[] obj = GameObject.FindObjectsofType(typeof(DemoScript));
for(int i=0;i < obj.Count;i++) { obj[i].XXX = XXX } ?
Hi,
Sorry about that. But it doesnt take the anwer I type. You are correct about the loop. But use obj.Length ins$$anonymous$$d of count. print(obj[i]), will for example will print all the gameobjects. Hope this helps :)