This week, once we made the final finishing touches to Amazing Racer, we took at look at a small project which introduced a number of new concepts, which are very useful when building games:
- Creating objects at run-time
- Creating a coroutine
- Using random values
- Using array parameters to specify multiple values
To create object at run-time, we saw the Instantiate method. This method is provided with a reference to an existing game object or prefab and it will create a new copy of it in the scene. Optionally, a new position and a new rotation can be specified for the duplicated object. The Unity documentation has more information on Instantiate.
A coroutine is a special kind of method. It is a method that can do some work, relinquish control temporarily to the game engine for a period, and then continue from where it left off. It has the special return type of IEnumerator. By calling yield return it can relinquish control. By calling yield return new WaitForSeconds(n) it can relinquish control for a specific period of time. To start a coroutine, we use the StartCoroutine method. You can read the Unity documentation for more information on coroutines.
We saw how Random.Range(min, max) can be used to give a random value between a maximum and minimum. This randomness can add interest and naturalism to our scene. The Unity manual reference for the Random class is here. You will see that there are many other ways to get random values, apart from the Range method.
Finally, we saw how a parameter can be an array. We used an array to specify multiple game objects which could be created by our source object. In the source our property objectsToSpawn is an array, as indicated by the square brackets .
In the inspector panel, we can see Objects To Spawn which offers a size that can be set, in this case we’ve entered 3, and as many boxes as the array is large.
The Coroutine Test project is available here.
Our completed Amazing Racer project is available here.
Finally, I was asked to provide the completed Roll-A-Ball project too. That’s here.
All these projects are compatible with Unity V5.3.2f1.
We look forward to seeing you in two weeks! Remember to work on your game ideas over the break!