As you know Unity a bit, have you heard of Vector3 already? If you haven't, I will explain it very briefly. Vector3 represents a 3D vector and a point or direction. The Unity documentation says:
"This structure is used throughout Unity to pass 3D positions and directions around. It also contains functions for doing common vector operations."
Feel free to study more about Vector3 at this link: http://docs.unity3d.com/ScriptReference/Vector3.html. If you are not a math master, you will feel confused now. All I want you to remember right now is that Vector3 can be used to store the position of a game object in 3D space. It contains the X, Y, and Z positions in 3D space. That's it! Don't bother yourself with too much information about 3D vectors at this stage; it is a massive subject.
Line 39 is where we are creating a new Vector3 type variable to store the position we will move our level position to in the next few lines.
The if
statement on line 42 checks whether the piece we are adding to the level is the very first piece in the level. If this statement is true, then line 44 is executed, assigning the levelStartPoint.position
value to the spawnPoint
local variable.
In other words, if the pieces
list count is 0
, it means that we are adding the very first piece to the level, and its position will be the same as that of the levelStartPoint
variable.
If we do not add the first piece to the level, the piece.Count
value will be different from 0
and line 48 will be executed instead of line 44.
It is crucial that you understand fully how line 48 works. In this line, we are assigning the value to spawnPoint
. What value? That's a good question. To get the position, we are looking back into the pieces
list—at the last element stored in that list. The last element in the pieces
list will be always the last level piece that is already placed in the level, so we can use the exitPoint.position
value here. Remember the LevelPiece
class? The ExitPoint
is the position where the next piece will connect to; you learned about this a few pages back.
Great! So at this point, we know that the spawnPosition
value should be set to either the initial position from which the level starts, or the exit point of the last piece in the level. All that we need to do now to make the newly spawned piece jump to the right position is assign its .transform.position
value. We do that in line 51. Line 52 adds the new piece to the list for easy access.
This was a tough phase in the game. I really hope you don't feel confused now. Don't worry too much if you do. Things will be much clearer when you see your LevelGenerator
working in the Scene view.