CTIN 289 - Interactive Snippets Library

Powered by 🌱Roam Garden

Lists

What if you have more than one thing to remember?

The pattern is htat you have a "manager" object, and that "manager" object has a List of things it is managing.

So you might have a GoombaManager script that keeps a List of Goombas.

A list is like an array, but smarter.

List

Grows and shrinks

Can search for specific members

Can add or remove from the middle

Can be sorted

Array

Keeps the size it was given when it was created

You have to loop over it to find things

You have to make a new aray and copy what you need into it

You have to make a new array and sort it yourself

//Lists Example

Light[] lightArray;
lightArray = FindObjectsOfType<Light>();

// make a new list and copy the contents of this array into it
List<Light> lightList;
lightList = new List<Light>(lightArray);

// Declare and set up a List of whatever type you need
// Instantiate the new thing and save a reference
// Add the reference to the List

// Says: I need a list at some point.
// It's like you're thinking about needing groceries, so you get out your resuable grocery bag.
List<Enemy> enemyList;

// Says: I'm making the list now.
// This is like getting out a piece of paper to write down your grocery list, but there's nothing in it yet.
enemyList = new List<Enemy>();

//do this five times
for (int i=0; i<5; i++)
{
  // Make a new copy of the enemy prefab and keep a reference to it (instead of forgetting it forever)
  GameObject newEnemyGO = Instantiate(enemyPrefab);
  // Ask the newly created GameObject for a script component called Enemy
  Enemy newEnemy = newEnemyGO.GetComponent<Enemy>();
  // Add this copy of the Enemy script to the List
  enemyList.Add(newEnemy);
}

// This works the same way for other components.

List<Light> listOfLights;
listOfLights = new List<Light>();

for(int i = 0; i < 5; i++)
{
  GameObject newLightGO = Instantiate(lightPrefab);
  Light newLight = newLightGO.GetComponent<Light>();
  listOfLights.Add(newLight);
}

// Same for transforms!

List<Transform> enemyTransforms;
enemyTransforms = new List<Transform>();

for (int i=0; i<5; i++)
{
  GameObject newEnemyGO = Instantiate(enemyPrefab);
  Transform newEnemyTransform = newEnemyGO.transform;
  enemyTransform.Add(newEnemyTransform);
}