Game Development Reference
In-Depth Information
The List class
If you need an unordered, sequential list of items of any single data type, that is,
a list that grows and shrinks to match the size of the stored data, then the List
class is ideal. List is especially good to add and remove items and sequentially
iterating through all stored items. In addition, the List objects are editable from
the Unity Object Inspector. The following code sample 6-1 uses a sample C# file
Using_List.cs :
01 using UnityEngine;
02 using System.Collections;
03 using System.Collections.Generic;
04 //----------------------------------------
05 //Sample enemy class for holding enemy data
06 [System.Serializable]
07 public class Enemy
08 {
09 public int Health = 100;
10 public int Damage = 10;
11 public int Defense = 5;
12 public int Mana = 20;
13 public int ID = 0;
14 }
15 //----------------------------------------
16 public class Using_List : MonoBehaviour
17 {
18 //----------------------------------------
19 //List of active enemies in the scene
20 public List<Enemy> Enemies = new List<Enemy>();
21 //----------------------------------------
22 // Use this for initialization
23 void Start ()
24 {
25 //Add 5 enemies to the list
26 for(int i=0; i<5; i++)
27 Enemies.Add (new Enemy());
//Add method inserts item to end of the list
28
29 //Remove 1 enemy from start of list (index 0)
30 Enemies.RemoveRange(0,1);
31
32 //Iterate through list
33 foreach (Enemy E in Enemies)
34 {
35 //Print enemy ID
 
Search WWH ::




Custom Search