Get GameObject from List based on attached script or assigned name

Hi, I was wondering if there was any way to identify an script-created GameObject based on its attached script OR its assigned name in a list. For example:

newEntry = new GameObject("FirstEntry");
newEntry.AddComponent<EntryScript>();
newEntry.GetComponent<EntryScript>().ID = 1;
entryList.Add(newEntry);

newEntry = new GameObject("SecondEntry");
newEntry.AddComponent<EntryScript>();
newEntry.GetComponent<EntryScript>().ID = 2;
entryList.Add(newEntry);


entryList.Remove(?);

If I wanted to remove only FirstEntry, how would I go about that? Im trying to dynamically create a LOT of GameObjects (some different, some duplicates) and save them in lists, but I’m not sure how to identify them after I add them. entryList.Remove(newEntry) logically only removes the last added newEntry.

Can you not do this?

for (int i = 0; i < entryList.Count; i++)
{
    if (entryList*.GetComponent<EntryScript>().ID = 1)*
  • entryList.RemoveAt(i);*
    }

Put “break” after the RemoveAt to stop the for loop iterating again if it has performed a removal. For example:

if (check ID){
     entryList.RemoveAt(i);
     break;
}

What @BackslashOllie posted, but with break; and == (also in descriptive method for cleaner code):

private void RemoveFirstEntryWithID(int id)
{
    for (int i = 0; i < entryList.Count; i++)
    {
        if (entryList*.GetComponent<EntryScript>().ID == id)*

{
entryList.RemoveAt(i);
break; // jumps out of the for loop after entry removal
//i–; would go here if we didn’t break
}
}
}
By the way, consider making your entryList to List<EntryScript> entryList instead if it’s applicable, so you can do:
newEntry = new GameObject(“FirstEntry”).AddComponent();
newEntry.ID = 1;
entryList.Add(newEntry);
newEntry = new GameObject(“SecondEntry”).AddComponent();
newEntry.ID = 2;
entryList.Add(newEntry);
And then simply if (entryList*.ID == id).*