- Home /
 
               Question by 
               NinjaSu · Apr 20, 2013 at 11:43 PM · 
                listarraysfindgame objectfind-gameobject  
              
 
              Searching a List of GameObjects by name
So I have a list of gameObjects, how would I efficiently get the gameObject with a name?
For example
 List<GameObject> list = new <GameObject>();
 GameObject temp = list.Find("Sword");
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by dorpeleg · Apr 21, 2013 at 12:25 AM
Just use loop:
 for(int i=0; i<list.Count; i++){
     if(list[i].name == "Sword") {
         temp = list[i];
         break;
     }
 }
can't think of a more efficient way.
Good and simple solution. If you looking for one GameObject, break the for cycle once you found.
Answer by ZGTR · May 12, 2015 at 09:34 AM
Easily done using Linq:
   using System.Linq;
   GameObject temp = list.Where(obj => obj.name == "Sword").SingleOrDefault();
This will return your game object if found. Otherwise, null. You have to import System.Linq though.
You can use .ToList() ins$$anonymous$$d of SingleOrDefault() and that will return a collection of all objects named "Sword"
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                