I have used the word Instantiate
a few times before. What does it mean? Instantiating simply means creating a copy of the object. Yet again, I encourage you to go back to Scripting Reference and read about Instantiate
.
Line 36 is where we are using Instantiate:
LevelPiece piece = (LevelPiece)Instantiate(levelPrefabs[randomIndex]);
In this line, we are creating a copy of one of the levelPrefabs
elements stored under the randomIndex
value. We assign the instantiated object straightaway to the local piece variable. So basically, this is the line that creates an exact copy of the prefab and places it in the scene.
When instantiating a game object, we are creating a copy of the object. Unity, however, doesn't copy its parent assignment, so the instantiated object will be created on top of the hierarchy. To correct this, we set the parent to the piece object using the transform.SetParent
function on line 37.
Great! We know how to create a copy of a game object and assign a parent to it. The next step is to position the newly created level piece at the right place in our level. Let's try to understand the rest of the AddPiece
function line by line.