• 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
21
Question by HeywoodFloyd · Aug 05, 2010 at 08:48 PM · gameobjectfind-gameobject

How do I find all game objects with the same name?

The GameObject.Find method returns a single object, but Unity allows you to give multiple objects the same name. How can I find all instances of an object that have the same name?

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

7 Replies

· Add your reply
  • Sort: 
avatar image
34

Answer by skovacs1 · Aug 05, 2010 at 09:15 PM

There are several ways to find multiple objects.

By Tag (recommended)

FindGameObjectsWithTag will find game objects with the specified tag (not name), meaning all of the objects you are looking for would have to have the same tag. This returns an array of GameObjects which you can iterate through to check the name if you need to use the name and cannot simply use tags.

Unity js

for(var fooObj : GameObject in GameObject.FindGameObjectsWithTag("foo"))
{
    if(fooObj.name == "bar")
    {
        //Do something...
    }
}

Unity mono

foreach(GameObject fooObj in GameObject.FindGameObjectsWithTag("foo"))
{
    if(fooObj.name == "bar")
    {
        //Do Something
    }
}

By Type

FindObjectsOfType will find all objects of a certain type, meaning that all of these objects will need to have the same type. This returns an array of Objects which you can treat as the type you searched for.

Unity js

//You probably want a more specific type than GameObject
for(var gameObj : GameObject in GameObject.FindObjectsOfType(GameObject))
{
    if(gameObj.name == "bar")
    {
        //Do something...
    }
}

C#

//You probably want a more specific type than GameObject
foreach (var gameObj in FindObjectsOfType(typeof(GameObject)) as GameObject[])
{
    if(gameObj.name == "bar")
    {
        //Do something...
    }
}
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
8

Answer by IsaiahKelly · Oct 05, 2016 at 11:41 PM

Find all Objects With Name:

 var objects = Resources.FindObjectsOfTypeAll<GameObject>().Where(obj => obj.name == "Name");

This returns a list called "Objects" containing all active and inactive game objects with a name matching the provided string.

Note: This code requires LINQ Queries.

 using System.Linq;
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
3

Answer by hristo991 · Jul 11, 2014 at 04:54 PM

Four years later... HEY GUYS I FOUND A WAY.... silence....

Now, seriously, here is my way of finding all objects with the same name. Since there is no direct way of doing it the code is quite big:

here is my whole in-game console script (not finished):

 var display : boolean;
 var actionIndex : int;
 var AINA : String[] = ["Level", "Object", "Variable", "Command", "PlayerPrefs"];
 var objectName : String;
 var objectIndex : int;
 var checkIndex : int;
 var foundObjects : GameObject[];
 var variableName : String;
 var command : String;
 var playerPrefsName : String;
 var playerPrefsInt : int;
 var playerPrefsFloat : float;
 var playerPrefsString : String;
 var levelToLoad : String;
 var TCS : Component[]; //temporary component store
 var TCSI : int; //temporary component store index
 
 function Start () {
     TCS = new Component[1];
 }
 
 function Awake () {
     DontDestroyOnLoad(gameObject);
 }
 
 function Update () {
     if(Input.GetKey(KeyCode.LeftControl))
     {
         if(Input.GetKeyDown(KeyCode.F1))
         {
             if(!display)
             {
                 display = true;
             }
             else
             {
                 display = false;
             }
         }
     }
 }
 
 function OnGUI () {
     if(display)
     {
         GUILayout.BeginArea(Rect(0,0,512,250),"","Box");
         GUILayout.BeginArea(Rect(5,5,502,35));
         actionIndex = GUILayout.SelectionGrid(actionIndex,AINA,AINA.Length,GUILayout.Height(35));
         GUILayout.EndArea();
         
         if(actionIndex == 0)
         {
             levelToLoad = GUI.TextField(Rect(5,50,502,25),levelToLoad);
             if(GUI.Button(Rect(5,80,502,25),"Load"))
             {
                 Application.LoadLevel(levelToLoad);
             }
         }
         
         if(actionIndex == 1)
         {
             objectName = GUI.TextField(Rect(5,50,302,25),objectName);
             if(GUI.Button(Rect(312,50,95,25), "By tag"))
             {
                 FindObjectsWithTag();
             }
             if(GUI.Button(Rect(412,50,95,25), "By name"))
             {
                 FindAllObjects();
             }
         }
         
         
         GUILayout.EndArea();
     }
 }
 
 function FindObjectsWithTag () {
     var objects = GameObject.FindGameObjectsWithTag(objectName);
     foundObjects = new GameObject[objects.Length];
     foundObjects = objects;
 }
 
 function FindAllObjects () {
     var objectsn = GameObject.FindObjectsOfType(GameObject);
     for(var f = 0; f < objectsn.Length; f++)
     {
         if(objectsn[f].name != objectName)
         {
             objectsn[f] = null;
         }
     }
     for(var i = 0; i < objectsn.Length; i++)
     {
         if(objectsn[i] != null)
         {
             checkIndex ++;
         }
     }
     foundObjects = new GameObject[checkIndex];
     checkIndex = 0;
     for(var a = 0; a < objectsn.Length; a++ )
     {
         if(objectsn[a] != null)
         {
             foundObjects[checkIndex] = objectsn[a];
             checkIndex++;
         }
     }
     checkIndex = 0;
     
 }
 
 function ResizeTCS () {
     TCS = new Component[TCS.Length + 1];
 }

Now, the important part:

 var objectName : String;
 var checkIndex : int;
 var foundObjects : GameObject[];
 function FindAllObjects () {
     var objectsn = GameObject.FindObjectsOfType(GameObject); //get all objects
     for(var f = 0; f < objectsn.Length; f++) //filter the objects that don't match
     {
         if(objectsn[f].name != objectName)
         {
             objectsn[f] = null;
         }
     }
     for(var i = 0; i < objectsn.Length; i++) //check how may objects are left in there
     {
         if(objectsn[i] != null)
         {
             checkIndex ++;
         }
     }
     foundObjects = new GameObject[checkIndex]; //resize
     checkIndex = 0;
     for(var a = 0; a < objectsn.Length; a++ ) //apply the objects to a new array
     {
         if(objectsn[a] != null)
         {
             foundObjects[checkIndex] = objectsn[a];
             checkIndex++;
         }
     }
     checkIndex = 0;
     
 }


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 melwei · Feb 07, 2016 at 09:37 AM 0
Share

Nice method, but not very handsome....

avatar image
2

Answer by melwei · Feb 07, 2016 at 09:57 AM

If you really want to work with the names, this c# void gives the array of all GameObjects with the specific name.

 GameObject[] FindGameObjectsWithName(string name){
         int a = GameObject.FindObjectsOfType <GameObject>().Length;
         GameObject[] arr=new GameObject[a];
         int FluentNumber = 0;
         for (int i=0; i<a; i++) {
             if (GameObject.FindObjectsOfType<GameObject> () [i].name == name) {
                 arr [FluentNumber] = GameObject.FindObjectsOfType<GameObject> () [i];
                 FluentNumber++;
             }
         }
         Array.Resize (ref arr, FluentNumber);
         return arr;
     }
Comment
Add comment · Show 3 · 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 melwei · Feb 07, 2016 at 09:57 AM 1
Share

5 years later....

avatar image Diet-Chugg melwei · Aug 31, 2016 at 05:25 PM 0
Share

GameObject.FindObjectsOfType is very expensive to call. It should be used as little as possible. It should also be noted that this call does not give you inactive instances in the scene. So doing it that way does not give you all instances of the same name. However if I would do it that way I'd at least make it efficient like this:

GameObject[] FindGameObjectsWithName(string name) { GameObject[] gameObjects = GameObject.FindObjectsOfType(); GameObject[] arr = new GameObject[gameObjects.Length]; int FluentNumber = 0; for (int i = 0; i < gameObjects.Length; i++) { if (gameObjects[i].name == name) { arr[FluentNumber] = gameObjects[i]; FluentNumber++; } } Array.Resize(ref arr, FluentNumber); return arr; }

View my answer for a solution that includes inactive gameobjects.

avatar image Diet-Chugg Diet-Chugg · Aug 31, 2016 at 05:36 PM 1
Share

Forgot to hit the Code Sample button. Here's a more readable version:

 GameObject[] FindGameObjectsWithName(string name)
 {
     GameObject[] gameObjects =  GameObject.FindObjectsOfType<GameObject>();
     GameObject[] arr = new GameObject[gameObjects.Length];
     int FluentNumber = 0;
     for (int i = 0; i < gameObjects.Length; i++)
     {
         if (gameObjects[i].name == name)
         {
             arr[FluentNumber] = gameObjects[i];
             FluentNumber++;
         }
     }
     Array.Resize(ref arr, FluentNumber);
     return arr;
 }

avatar image
1

Answer by qJake · Aug 05, 2010 at 09:13 PM

They don't provide this functionality for you because Find() is not very performant, even for one object (let alone returning an array of objects). You're also probably not supposed to be naming similar objects the exact same if you want to group them. Instead, you should use a tag, and GameObject.FindGameObjectsWithTag() which does return an array of game objects with that particular tag (not to mention it's faster, and the correct way to "group" game objects).

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 yoyo · May 09, 2014 at 10:36 PM 2
Share

"You're also probably not supposed to be naming similar objects the exact same" -- which is an excellent point, but validating this requires a FindAll method! :-p

  • 1
  • 2
  • ›

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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



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

How to dynamically construct a reference to a game object by name 2 Answers

GameObject.Find/WithTag returns null 1 Answer

Which is faster, GameObject.Find or GameObject.FindWIthTag? 2 Answers

How to find UI in code c# (button, Panel etc) 2 Answers

using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges