Game Development Reference
In-Depth Information
The following code sample 6-23 demonstrates an alternative approach to the
preceding code sample 6-22 using Linq:
01 using UnityEngine;
02 using System.Collections;
03 using System.Collections.Generic;
04 using System.Linq;
05 //-------------------------------------------------
06 public void FindEnemiesLinqWay()
07 {
08 //Get all enemies in scene
09 Enemy[] Enemies = Object.FindObjectsOfType<Enemy>();
10
11 //Perform search
12 Enemy[] FilteredData = (from EnemyChar in Enemies
13 where EnemyChar.Health <= 50 && EnemyChar.Defense < 5
14 select EnemyChar).ToArray();
15
16 //Now we can process filtered data
17 //All items in FilteredData match search criteria
18 foreach(Enemy E in FilteredData)
19 {
20 //Process Enemy E
21 Debug.Log (E.name);
22 }
23 }
24 //-------------------------------------------------
The following are the comments for code sample 6-23:
Lines 03-04 : To use Linq, you must include the System.Collections.
Linq namespace, and to use List objects, you must include the System.
Collections.Generic namespace.
Lines 12-14 : The main body of Linq code occurs here. It consists of three
main parts. First, we indicated the items to pick from the source data,
specifically, enemy objects from the data set Enemies . Second, we defined
the criteria to search for, specifically where EnemyChar.Health <= 50 &&
EnemyChar.Defense < 5 . Then, when the criterion is met, we selected that
object to add to the results; we selected EnemyChar . Finally, we converted the
results to an array with the ToArray function.
 
Search WWH ::




Custom Search