0

I tried making a game where the player has to jump over obstacles . I want the obstacles to get duplicated to be at a random position.I wrote the rest of the script in C#.I'm a beginner so I don't know much C#

1 Answers1

2

Firstly, you should create a Prefab of your obstacle(s), since you want to duplicate it. You can do this by dragging it from the Scene Hierarchy into to the Project>Assets Folder.

Afterwards, create an Empty Game Object inside your Scene, and add a script to it, you could call it something like ObstacleSpawner.

I don't want to give you a complete answer... But in the script, you will have a public GameObject obstacle; (or public GameObject[] obstacle; if there's more than one). After saving the script, the inspector window of the Empty Game Object > ObstacleSpawner (Script) will now have something called "Obstacle" : "None (Game Object)" inside the box. You can drag the prefab you made of the obstacle inside there.

To spawn the obstacle, go back to the script. And inside the Start() { } function, use the Instantiate function. It takes 3 arguments, 1st is the GameObject, so that would be the obstacle. 2nd is a Vector2(x,y) or Vector3(x,y,z) position, 3rd is a rotation (Quaternion.Euler(x,y,z)).

To simply spawn the obstacle where the Empty Game Object is, use Instantiate(obstacle, transform.position, transform.rotation);

I'm assuming this is 2d, so you can randomly change the x value of the Vector2 position to make it move side to side, the following example would return a random the x position between 0 and 20 units on the x-axis from the Empty Game Object: float num = Random.Range(0, 20);.

Instantiate can be used inside a for loop to be performed more than once (but make sure to change the values so that each object is instantiated at different positions).

JTizzle
  • 117
  • 7