0

I have a function that contains a list that gets called externally. I want to find objects that is containing within the list through the object's name. I would like to get the object's property like component it contains. How do I do this?

public string nameOfObj;
void Start () {
      //Call function here
    GetObjects(nameOfObj);

   }

    public List<GameObject> GetObjects(String obj){
        return new List<GameObject>();
    }

Vika
  • 419
  • 1
  • 13
  • Would this answer your question [Filtering collections in C#](https://stackoverflow.com/questions/26196/filtering-collections-in-c-sharp) this was the fist hit when googling for [`filter list c#`](https://www.google.com/search?q=filter+list+c%23) ... – derHugo May 16 '22 at 12:27

1 Answers1

1

You could do this using a Where function.

using System.Linq;

List<GameObject> objectsToSearch = new List<GameObject>();

public List<GameObject> GetObjects(string obj){
    return objectsToSearch.Where(a => a.nameOfObj == obj).ToList();
}

As a warning, this will not be the most performant way of getting the data. Depending on how often this is getting called and how much data will be in the list getting searched, this method could cause issues down the road.

Micah C
  • 86
  • 4
  • hi thank you. What is "a.nameOfObj" here? – Vika May 16 '22 at 12:10
  • @Vika probably `a.name`. have in mind that not everyone here knows the Unity API ;) We expect a little bit of effort to apply solutions to your specific environment and use case .. the idea from this answer should be clear ;) – derHugo May 16 '22 at 12:24
  • for a search you also might want to change `==` to e.g. `Contains` or `StartsWith` according to your desired behavior – derHugo May 16 '22 at 12:25