Create a folder named “Prefabs” in the Assets section. Click on the road from the Node Hierarchy just on top and drag it to the Prefabs folder just created. This will create a new road prefab. Prefabs can be used to create multiple instances of the same object. We need to do this so that we can generate the road systematically.
Right click on the Game scene->create->Empty Node. Name the new Node as “GameManager”. We will use the game manager to manager several aspects of our game including the generation of the road.
The GameManager should not be in any folder and should be just as shown in the figure above.
Go to the assets section to create the script for the GameManager. Right Click the Scripts folder->create->TypeScript->New Component. Name the script as “GameManager” as shown in the screenshot. Open the GameManager script and add the following code.
import { _decorator, Collider, Component,
instantiate, Node, Prefab } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('GameManager')
export class GameManager extends Component {
// we will use this to drag the prefab to the game manager in the editor
@property(Prefab)
roadPrefab:Prefab = null;
onLoad(){
// Instantiate 100 instances of the prefab using a for loop
for (let i = 0; i < 100; i++) {
//instantiates the road but is not yet added to the scene
const instantiatedNode = instantiate(this.roadPrefab);
//since we know the road is a 10 by 10 in size,
//we generate a new road every 10 spaces going backwards(-10)
instantiatedNode.setPosition(0, 0, i * -10);
// Add the instantiated node to the current scene
this.node.addChild(instantiatedNode);
}
}
update(deltaTime: number) {
}
}
We want to generate the road prefab systematically so we need to create a property that can allow us to drag the road prefab onto the GameManager node. roadPrefab in this case is the actual road prefab we created in the project.
We want the road to be generated as the game scene load so we write our code in the “onLoad” function. We use a for loop with 100 iterations to generate the 100 road blocks. In the for loop, we generate the road from the prefab and store it as “instantiatedNode”. We set the position pushing it towards the back of any other road block by 10 spaces i.e., -10. The first road block will be set at a z axis of 0 then the second one at -10 then the third one at -30 and so on and so forth. Once the position is set for each node, we then add the node to the scene.
Click on the GameManager in the Node Hierarchy and drag the road prefab from the prefabs folder to the “Road Prefab” section of the GameManager as shown in the figure below.
Simulate the project and verify that the road is being generated successfully