Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Random Map Generator

Discussion in 'Scripting' started by xxfelixlangerxx, Feb 20, 2019.

  1. xxfelixlangerxx

    xxfelixlangerxx

    Joined:
    Feb 6, 2019
    Posts:
    31
    Hey,
    I am programming my first game but got kinda stuck. I have some prefabs wich i want to cycle in a random order. But my platforms dont cycle.
    This is my problem code



    Code (CSharp):
    1. [SerializeField]
    2.     private GameObject[] _plattformprefabs;
    3.     public float Platformoffset = 40f;
    4.     public float numberofplatforms = 0;
    5.     public float Randomnumber = 34f;
    6.  
    7.  
    8.  
    9.     void Update()
    10.     {   //this is the problematic code
    11.         for (int i = 0; i < 4; i++)
    12.         {   // i need to place my platforms in random orders how do i do that?
    13.             Instantiate(_plattformprefabs[i], new Vector3(0, 0, numberofplatforms * Randomnumber + Platformoffset), Quaternion.Euler(0, 0, 0));
    14.             numberofplatforms = numberofplatforms + 1;
    15.         }
    16.     }
    Thanks ahead
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    Here's your error:

    Code (CSharp):
    1. Instantiate(_plattformprefabs[i]
    Use random index instead of i when retreiving a prefab from the array.

    Code (CSharp):
    1. var index = Random.Range(0, _plattformprefabs.Length);
     
  3. xxfelixlangerxx

    xxfelixlangerxx

    Joined:
    Feb 6, 2019
    Posts:
    31
    I am sorry but it seems like your code dosnt work or i am just stupid.
    Becaus when i use this code the Map is still the same.
    Code (CSharp):
    1.  void Update()
    2.     {
    3.         for (int i = 0; i < 4; i++)
    4.         {
    5.             var index = Random.Range(0, _plattformprefabs.Length);
    6.             Instantiate(_plattformprefabs[i], new Vector3(0, 0, numberofplatforms * Randomnumber + Platformoffset), Quaternion.Euler(0, 0, 0));
    7.             numberofplatforms = numberofplatforms + 1;
    8.          
    9.         }
    10.     }
     
  4. QJaxun

    QJaxun

    Joined:
    Sep 30, 2016
    Posts:
    24
    Try _platformprefabs[index]
     
  5. xxfelixlangerxx

    xxfelixlangerxx

    Joined:
    Feb 6, 2019
    Posts:
    31
    Sorry but I dont seem to understand what should i replace with _platformprefabs[Index]
     
  6. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    this:
    Code (CSharp):
    1. _platformprefabs[i]
     
  7. xxfelixlangerxx

    xxfelixlangerxx

    Joined:
    Feb 6, 2019
    Posts:
    31
    Nice! It works thanks a lot!!!