- Home /
Alternatives to GameObject.Find() and GameObject.FindObjectsOfType() to also get disabled objects/components
Hi,
I guess it's been covered many times already, but I can't really find a solution in Unity Answers or the Forum or Google.
I'm looking for a metod or scrap of code that allow me to get a result comparable to GameObject.Find and GameObject.FindObjectsOfType that also takes into account disabled objects or components in the scene hierarchy.
I saw there are the "All" alternatives to these methods, but I don't know how to mask their results to only get objects in the scene.
Premise: I need to use these in a persistent singleton which also executes in editor mode, so I can't assign objects or references by hand. I get all the references on the Awake method. Also, the game designer could forget to enable certain objects before saving the scene, and I still haven't found a way to enable the relevant object before saving. Please also note that this Singleton (which is actually one of the different managers on a persistent gameobject) is only available during scene creation and it will be removed (or deleted by a previously existing singleton of the same type) when saving the final version of the scene. It gets added to each scene just to help the level designer.
Could you please help me?
Using these methods is not recommended anyway .... Can't you set the reference at "compile time" using the Inspector ?
No, I can't. I added a necessary premise to the description of the answer:
Premise: I need to use these in a persistent singleton which also executes in editor mode, so I can't assign objects or references by hand. I get all the references on the Awake method. Also, the game designer could forget to enable certain objects before saving the scene, and I still haven't found a way to enable the relevant object before saving. Please also note that this Singleton (which is actually one of the different managers on a persistent gameobject) is only available during scene creation and it will be removed (or deleted by a previously existing singleton of the same type) when saving the final version of the scene. It gets added to each scene just to help the level designer.
Answer by IsaiahKelly · Mar 13, 2017 at 07:35 PM
Find all GameObjects in the Active Scene
Here's a simple method to find all active and inactive objects in the current scene. I also added a check to exuded hidden objects since you usually don't want those and they can include internal Unity editor stuff that you shouldn't touch.
private static IEnumerable<GameObject> FindSceneGameObjects()
{
return Resources
.FindObjectsOfTypeAll(typeof(GameObject))
.Cast<GameObject>()
// Only get objects from the active scene.
.Where(go => go.scene == SceneManager.GetActiveScene())
// Ignore hidden objects.
.Where(go => (go.hideFlags & HideFlags.HideInHierarchy) != HideFlags.HideInHierarchy);
}
Note: Requires the use of LINQ (System.Linq)