- Home /
How to search for corresponding items in List?
This is my class:
public class EnemyInfo
{
public GameObject enemy;
public int threatLevel;
public EnemyInfo(GameObject Enemy, int ThreatLevel)
{
enemy = Enemy;
threatLevel = ThreatLevel;
}
}
I setup 2 variables:
GameObject target;
public List<EnemyInfo> enemyList = new List<EnemyInfo>();
Lets say I set a target:
target = enemyList[0].enemy;
How can I find the corresponding "threatLevel" value to target without explicitly calling it, like below:
enemyList[0].threatLevel;
Instead, I am trying to search through my list for the gameobject that matches "target" and retrieve the corresponding threatLevel value? I am stuck with the syntax. Is a for statement required or is there a quicker way find it?
Any help appreciated, thanks.
Answer by LazyElephant · Dec 24, 2015 at 10:00 AM
The List class has a build in Find function. For your example, you could use it in the following way:
EnemyInfo enemyInList = enemyList.Find( x => x.enemy==target);
This will find the first occurrence of the target in the list. If your list can contain duplicates of the same object, List also has a FindAll function.
Thanks, it worked. This is my first time using Lists of my class. Very useful stuff once you get past the syntax barriers.