Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by ronronmx · Oct 23, 2011 at 07:14 PM · layersfindlayer

How to find all objects in specific layer?

I know how to do that with tags, but in my case I would need to use layers since I'm already using tags for other purposes on those objects.

Is there a way to return the amount of objects in a specific layer?

Thanks for your time! Stephane

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

4 Replies

· Add your reply
  • Sort: 
avatar image
12
Best Answer

Answer by Eric5h5 · Oct 23, 2011 at 07:39 PM

There's no built-in function, so you have to make your own. You can get all gameobjects, and iterate through them to find the ones with the specified layer, like this:

 function FindGameObjectsWithLayer (layer : int) : GameObject[] {
     var goArray = FindObjectsOfType(GameObject);
     var goList = new System.Collections.Generic.List.<GameObject>();
     for (var i = 0; i < goArray.Length; i++) {
         if (goArray[i].layer == layer) {
             goList.Add(goArray[i]);
         }
     }
     if (goList.Count == 0) {
         return null;
     }
     return goList.ToArray();
 }
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ronronmx · Oct 24, 2011 at 02:13 AM 0
Share

Hi Eric5h5, thanks for your answer, it's really helpful. Is this pretty much what the "FindObjectsWithTag" function do? The reason I'm asking is because I wonder if the code you gave me above will be as fast as the "FindObjectsWithTag" function. In any case I would only do this on Awake or Start, so even if it's slower, I can live with it.

Again, thanks for your time! Stephane

avatar image Eric5h5 · Oct 24, 2011 at 08:56 PM 0
Share

I would assume so; or at least I can't think of a better way that it could be done offhand.

avatar image 3agle · Dec 11, 2012 at 03:30 PM 6
Share

Thanks Eric, this was useful, converted it to C#:

GameObject[] FindGameObjectsWithLayer (int layer) { GameObject[] goArray = FindObjectsOfType(typeof(GameObject)) as GameObject[]; List goList = new List(); for (int i = 0; i < goArray.Length; i++) { if (goArray[i].layer == layer) { goList.Add(goArray[i]); } } if (goList.Count == 0) { return null; } return goList.ToArray(); }

avatar image roberto_sc · Oct 24, 2013 at 12:06 AM 0
Share

@Eric5h5 I disagree, for sure that's not what FindObjectsWithTag and it's slower, as you can find on GameObject.Find documentation "for performance reasons it is recommended to not use this function every frame Ins$$anonymous$$d cache the result in a member variable at startup or use GameObject.FindWithTag" and on Object.FindObjectsOfType "please note that this function is very slow. It is not recommended to use this function every frame".

avatar image Eric5h5 · Oct 24, 2013 at 12:16 AM 0
Share

FindWithTag isn't all that much faster than Find. If you're doing any kind of find, it's standard practice to cache the results if you're going to be re-using them.

Show more comments
avatar image
4

Answer by scottmitting · Feb 03, 2013 at 03:53 AM

I needed a solution that would let me find all objects that were inactive, and I was doing it from an EditorWindow, so I had to take a different route, using GetComponentsInChildren() and supplying a root game object to check within:

 private static List GetObjectsInLayer(GameObject root, int layer)
 {
     var ret = new List();
     foreach (Transform t in root.transform.GetComponentsInChildren(typeof(GameObject), true))
     {
         if (t.gameObject.layer == layer)
         {
             ret.Add (t.gameObject);
         }
     }
     return ret;        
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ronronmx · Feb 26, 2013 at 03:50 AM 0
Share

Nice, thx for the code snippet, it will come in handy :)

avatar image
2
Wiki

Answer by roberto_sc · Oct 24, 2013 at 01:21 AM

For using inside the Update call, I suggest making a class and inheriting all your scripts from it instead of MonoBehaviour. In this class you can create caches specific to each layer:

 public class LayeredMonoBehaviour : MonoBehaviour
 {
     private static IDictionary<int, IList<GameObject>> layersCache = new Dictionary<int, IList<GameObject>>();
 
     /**
      * Returns a list of all (active/inactive) GameObjects of the specified layer. Returns null if no GameObject was found.
      */
     public static IList<GameObject> FindGameObjectsWithLayer(int layer)
     {           
         return layersCache[layer];
     }
 
     /**
      * Returns one GameObject with the specified layer. Returns null if no GameObject was found.
      */
     public static GameObject FindWithLayer(int layer)
     {
         var cache = layersCache[layer];
         if (cache != null && cache.Count > 0)
             return cache[0];
         else
             return null;
     }
 
     protected void Awake()
     {
         // careful: this code assumes that your GameObjects won't change layer during gameplay.
         IList<GameObject> cache;
         if (!layersCache.TryGetValue(gameObject.layer, out cache))
         {
             cache = new List<GameObject>();
             layersCache.Add(gameObject.layer, cache);
         }
 
         cache.Add(gameObject);
     }
 
     protected void OnDestroy()
     {
         layersCache[gameObject.layer].Remove(gameObject);
     }
 }

The disadvantage is that you'll have to override Awake and OnDestroy and call base's implementation if you intend to use these methods in your scripts; but in general this is a good strategy and during the development of your game you may find other stuff that you want to add to this parent class that you wouldn't be able to do with extension methods for the regular MonoBehaviour.

It's also important to note that it won't work for GameObjects that doesn't have any scripts attached to it!

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by twobob · May 19, 2015 at 07:18 PM

I wanted an editor solution that didn't make me specify root.

Layer 31 is hardcoded.

 using System.Collections;
 using System.Collections.Generic;
 using System.Linq;
 using UnityEditor;
 using UnityEngine;
 
 public class GetAllObjectsInLayer : MonoBehaviour 
 {
     
     public static int layer = 31;
     
     [MenuItem("Tools/Select Objects in Layer 31", false, 50)]
     public static void SelectObjectsInLayer()
     {
         var objects = GetSceneObjects();
         GetObjectsInLayer(objects, layer);
     }
 
      private static void GetObjectsInLayer(GameObject[] root, int layer)
      {
          List<GameObject> Selected = new List<GameObject>();
          foreach (GameObject t in root)
          {
              if (t.layer == layer)
              {
                  Selected.Add(t);
              }
          }
          Selection.objects = Selected.ToArray();
 
      }
 
     private static GameObject[] GetSceneObjects()
     {
         return Resources.FindObjectsOfTypeAll<GameObject>()
                 .Where(go => go.hideFlags == HideFlags.None).ToArray();
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How to find layer instead of tags 3 Answers

How to find a prefab in another scene? 1 Answer

Problem with layers impedes playing 1 Answer

Checking for collisions before changing layers 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges