Game Development Reference
In-Depth Information
This code effectively loops through all members, runs them through a conditional
if statement, and then, finally adds the enemy to a results array if it passes the
condition. The condition, in this case, is whether an enemy's health is less than
50 percent and their defense is less than 5:
//Get list of enemies matching search criteria
public void FindEnemiesOldWay()
{
//Get all enemies in scene
Enemy[] Enemies = Object.FindObjectsOfType<Enemy>();
//Filtered Enemies
List<Enemy> FilteredData = new List<Enemy>();
//Loop through enemies and check
foreach(Enemy E in Enemies)
{
if(E.Health <= 50 && E.Defense < 5)
{
//Found appropriate enemy
FilteredData.Add (E);
}
}
//Now we can process filtered data
//All items in FilteredData match search criteria
foreach(Enemy E in FilteredData)
{
//Process Enemy E
Debug.Log (E.name);
}
}
This code works insofar as it restricts a larger data set into a smaller one on the basis
of a specific criterion. However, Linq lets us achieve the same results with less code
and often greater performance. Linq is a high-level and specialized language to run
queries on data sets, including arrays and objects, as well as on databases and XML
documents. The queries are translated automatically by Linq, under the hood, into
an appropriate language for the data set used (for example, SQL for databases).
The aim is to extract the results we need into a regular array.
 
Search WWH ::




Custom Search