Spawning objects at random generated worldpoints

I'm new to unity 3d and I want to make a very simple obstacle course game. I don't want it to have multiple levels but instead there will be only one scene which will generate randomly each time someone starts the game.

This is a picture to better explain the idea:

enter image description here

In each highlighted section there will be a wall which will be generated every time the application starts and the player can only get through a gap which will be randomly generated in any of the areas a, b or c of each section. I tried looking this up but there wasn't really much of this example.

If have any questions, please don't hesitate. I'm always notified for responses.

Thanks for your time!

Upvotes: 0

Views: 599

Answers (1)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

Basic concept:

  1. Create a prefab from your obstacle
  2. Create a script (e.g. WallSpawner) with a couple of parameters (distance between each wall, possible positions, etc.) and attach it to an object in your scene (in your case Walls for example).
  3. In the Start or Awake method, create copies of your prefab with Instantiate and pass in the randomly picked position.

Example Script:

public class WallSpawner : MonoBehaviour
{
    // Prefab
    public GameObject ObstaclePrefab;

    // Origin point (first row, first obstacle)
    public Vector3 Origin;

    // "distance" between two rows
    public Vector3 VectorPerRow;

    // "distance" between two obstacles (wall segments)
    public Vector3 VectorPerObstacle;

    // How many rows to spawn
    public int RowsToSpawn;

    // How many obstacles per row (including the one we skip for the gap)
    public int ObstaclesPerRow;

    void Start ()
    {
        Random r = new Random();

        // loop through all rows
        for (int row = 0; row < RowsToSpawn; row++)
        {
            // randomly select a location for the gap
            int gap = r.Next(ObstaclesPerRow);
            for (int column = 0; column < ObstaclesPerRow; column++)
            {
                if (column == gap) continue;

                // calculate position
                Vector3 spawnPosition = Origin + (VectorPerRow * row) + (VectorPerObstacle * column);
                // create new obstacle
                GameObject newObstacle = Instantiate(ObstaclePrefab, spawnPosition, Quaternion.identity);
                // attach it to the current game object
                newObstacle.transform.parent = transform;
            }
        }
    }
}

Example parameters:

Parameters in the Editor

Example result:

Example Walls (5 per row)

Upvotes: 6

Related Questions