Skip to content

Instantly share code, notes, and snippets.

@radiatoryang
Created April 2, 2015 00:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radiatoryang/d9015870ce7ec66122ef to your computer and use it in GitHub Desktop.
Save radiatoryang/d9015870ce7ec66122ef to your computer and use it in GitHub Desktop.
simple demo of lists and foreach for my Recursive Reality VR class, spring 2015
using UnityEngine;
using System.Collections;
using System.Collections.Generic; // STEP 1 OF USING A LIST: include this line
// a "List" is like an Array
// an array = "immutable", it cannot be resized
// a list = dynamically resizable, elastic, will stretch or shrink based on item count
// demo: I'm going to instantiate spheres, track the spheres using a list, and
// modify all of the spheres inside the list
public class ListDemo : MonoBehaviour {
public Transform spherePrefab; // assign in Inspector
public List<Transform> mySpheres = new List<Transform>();
public List<Light> myLights = new List<Light>(); // you can declare a List of *anything*!!!
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.P) ) {
// instantiate a new clone, and remember it as "newSphereClone"
Transform newSphereClone = (Transform)Instantiate ( spherePrefab, Random.insideUnitSphere * 10f, Quaternion.Euler (0, 0, 0) );
// add the sphere to the list
mySpheres.Add ( newSphereClone );
// rename the sphere (for demo purposes)
newSphereClone.name = "Sphere" + mySpheres.Count.ToString ();
}
if ( Input.GetKeyDown (KeyCode.K) ) {
// a ForEach loop is good for doing a lot of things at once to a set of variables
foreach ( var eachSphere in mySpheres ) {
eachSphere.localScale *= 2f;
eachSphere.position += Vector3.up;
}
}
foreach ( var sphere in mySpheres ) {
sphere.localScale = Vector3.one * Mathf.Sin (Time.time );
// this will do something different based on each list item's unique properties
if (sphere.position.x > 0f) {
// do something
} else {
// do something else
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment