Prefabs, Loops, Arrays

📦 Unity packages from today's class:

  • Exercise from last class: Solar System Generator
  • In-class exercise: Spawn Random Prefab at Random Position
    • Spawn at random position within set maximum distance.
    • Spawn at random position within set min-max range along X Y and Z axes.
    • Spawn at random position selected from a given array of positions.

Before we begin...


Review from last class

  • Transform component and its properties
  • Vectors and how to use them
    • Vector math operations and method functions
    • Using vectors for procedural animation

Exercise from last class

How do we make a solar system that dynamically generates at the start of the scene:

  1. a random number of planets and moons;
  2. a set distance interval between each consecutive sibling planet?

Prefabs

Read about Prefabs in the Unity Manual.

Prefabs allow you to store a GameObject and its information (including its components, property values, child objects, etc.) into your Unity project folder as a reusable Asset.

This Prefab Asset can be used as a base template from which you can create and modify new Prefab instances in the scene.


How to create a Prefab from an existing GameObject in the scene

Click and drag the GameObject from the Scene Hierarchy into your project folder panel.

The GameObject should now be marked with a blue icon, and have an arrow button to the right of its name that leads you to the Prefab editor.

How To Make A GameObject Prefab


How to Instantiate a GameObject

We use the Instantiate() method function to spawn new instances of a GameObject in our scene.

Instantiate(someGameObject);


You could also pass a GameObject instance into a GameObject variable. This allows you to reference it later in your script.

GameObject obj = Instantiate(someGameObject);

//let's say we want to change the position of this instance
obj.transform.position = someVector;

//or set it to a new parent
obj.transform.parent = someParentObject;


The Instantiate() method can also be called in other ways that allow you to pass multiple parameters at once.

The Unity Scripting API lists all the different ways you can declare the Instantiate() function.

For example:

GameObject obj = Instantiate(
    spawnThisGameObject, //GameObject
    atSomePosition, //Vector3
    atSomeQuaternionRotation, //Quaternion
    underSomeParent); //Transform


Loops

Loop functions allow you to repeat an action multiple times.

Watch the Unity Tutorial below to learn about:

  • While loops
  • Do-while Loops
  • For Loops


... and one more video about Foreach Loops.


Arrays

Read about Arrays in the Unity Manual.

Arrays allow you to store multiple objects in a single variable.

Each object in an array is attached to an index number, starting from 0. This index number is used when calling this object from the array.

string[] fruits = {"apples", "pears", "oranges"};

// fruits[0] will return "apples"
// fruits[1] ... "pears"
// fruits[2] ... "oranges"


Every array has a Length property, which gives you the number elements in the array.

string[] fruits = {"apples", "pears", "oranges"};

Debug.Log("Length of fruits array: "+ fruits.Length); 
// console will print "Length of fruits array: 3".


Arrays cannot be resized while the project is running. If you need to resize a container of objects, either recreate the array to resize it, or use a List instead.


How to declare an array

Declare the type of variable that is being stored in the array, followed by square brackets [] .

float[] someFloats; // a private float array
private Transform[] someTransforms; // a private Transform array
public Vector3[] someVectors; // a public Vector3 array
[SerializeField] GameObject[] someGameObjects; // a private GameObject array that is visible in the Inspector.


You can initialise the array by:

  • using an array constructor method in your scripts;
    // Creates an array with 5 empty elements
    int[] numbers = new int[5]; 
    
    // Initialises array with elements numbers = {1, 2, 3, 4, 5};
    //OR declare and initialise at once int[] numbers = new int[] {1,2,3,4,5};

  • storing elements in the Inspector, if your array is either public OR private with a [SerializeField] attribute;


  • using a method that sets the contents of an array
    //stores all GameObjects in the scene with tag "Respawn" into the array
    GameObject[] respawns = GameObject.FindGameObjectsWithTag("Respawn");

In-class exercise

Write a script that instantiates multiple prefabs that are:

  1. chosen at random from an array; AND
  2. each set at a random position within a given scope. (i.e. nothing should be "out of bounds", OR objects should only spawn at very specific positions.)

(Hint: Try using:


Some course reminders