Search Unity

Random Map Generation

Discussion in 'Scripting' started by TechnoObi, Jul 29, 2014.

  1. TechnoObi

    TechnoObi

    Joined:
    Nov 30, 2013
    Posts:
    82
    Does anyone know, how I can create random generation with prefabs. Like so:
    I have 10 Prefabs. When I start the game, the first one should start at x=0, the second one at x=10m, and so on.
    How can I do that?
     
  2. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    here you go ;o
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RandomSpawn : MonoBehaviour
    5. {
    6.     public int SpawnAmount = 50;
    7.  
    8.     [SerializeField]
    9.     private GameObject[] PrefabArray;
    10.  
    11.     void Start()
    12.     {
    13.         int i = 0;
    14.         while(i < SpawnAmount)
    15.         {
    16.             Vector3 newPosition = new Vector3(i * 10, 0, 0);
    17.             Instantiate(PrefabArray[Random.Range(0, PrefabArray.Length)], newPosition, Quaternion.identity);
    18.             i++;
    19.         }
    20.     }
    21.  
    22. }
     
    Last edited: Jul 30, 2014
    rakkarage and Polymorphik like this.
  3. TechnoObi

    TechnoObi

    Joined:
    Nov 30, 2013
    Posts:
    82
    Thanks, it works 90% :D

    But sometimes it creates like 2 at x=0, and sometimes it creates 0. :-(
     
  4. dakka

    dakka

    Joined:
    Jun 25, 2010
    Posts:
    113
  5. TechnoObi

    TechnoObi

    Joined:
    Nov 30, 2013
    Posts:
    82
    It doesn't work either...
     
  6. dakka

    dakka

    Joined:
    Jun 25, 2010
    Posts:
    113
    Tested the code, works. Try a blank project, with just this code. New prefabs.