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

Question Randomize my Road

Discussion in 'Scripting' started by Nerer133, Dec 14, 2022.

  1. Nerer133

    Nerer133

    Joined:
    Jul 7, 2022
    Posts:
    2
    Hi!
    I have an issue with my project. I have 4 different prefabs and I want to put them in random order on my road.
    Kind of:
    1, 3, 2, 4, 2, 1 etc.

    I already have a code that put chosen prefabs to a List and put it on my Scene, but now I need to put it by hand and it's looping, so my road is kind of random... But not in way that i want it. I want to Unity add it automatically and for example throw away the last position of the list and randomly add new diffrent rather than last.

    And at least I want to Unity randomize my road in way that the same prefabs don't be side by side.
    For example:
    1, 2, 4, 4, 4, 3, 2, 1

    My Code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using UnityEngine;
    5.  
    6. public class RoadSpawner : MonoBehaviour
    7.    {
    8.         public List<GameObject> roads;
    9.         private float offset = 8f;
    10.  
    11.         void Start()
    12.         {
    13.              if (roads != null && roads.Count > 0)
    14.              {
    15.                   roads = roads.OrderBy(r => r.transform.position.z).ToList();
    16.              }
    17.         }
    18.  
    19.        public void MoveRoads()
    20.        {
    21.             GameObject moveRoad = roads[0];
    22.             roads.Remove(moveRoad);
    23.             float newZ = roads[roads.Count - 1].transform.position.z + offset;
    24.             moveRoad.transform.position = new Vector3(0, 0, newZ);
    25.             roads.Add(moveRoad);
    26.        }
    27.  
    28. }
     
    Last edited: Dec 14, 2022
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,623
    FYI: Here's how to post code on the forums.
     
  3. Nerer133

    Nerer133

    Joined:
    Jul 7, 2022
    Posts:
    2
    Done
     
    MelvMay likes this.
  4. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    I have no idea what this means, can you rephrase it?

    The easiest way to do this would be to just add them to the List one by one, and if the randomly generated one matches the previous one, reroll your random selection. There are other ways, easiest to figure them out is to Google "random array with no repeats".