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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Pick random scene from a list to load.

Discussion in 'Scripting' started by cristo, Jan 4, 2019.

  1. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Hi, I'd like to load a scene from a random array list, but I don't want an int between a min max random range. So in the code below it would load 1 or 5 or 7, not one of 7 ints between 1 and 7.
    Any insight would be great.


    Code (CSharp):
    1. public class SceneChangeRandomArray : MonoBehaviour
    2. {
    3.     //public void ChangeToSceneRandomArray(int[] rArrayRandom)
    4.      public void ChangeToSceneRandomArray()
    5.     { }
    6.  
    7.         int[] Levels = new int[] { 1, 5, 7 };
    8.         int MyIndex = Levels[Random.Range(0, Levels.Length)];
    9.         Application.LoadLevel(Levels);
    10.      
    11.  }
    12.  
    13.  
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    It seems to me that you are already doing what you want. You have a list with n ints and you randomly select one of them. Just load that index:
    Code (csharp):
    1.  
    2. Application.LoadLevel(MyIndex);
    3.  
     
    cristo likes this.
  3. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Thanks for the feedback.
     
  4. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    You're missing one step, on the last line where you said "LoadLevel" you're sending it the list of ints as an argument, it's meaningless to it, you just need to tell it to use "MyIndex" like so:
    Code (CSharp):
    1. Application.LoadLevel(Levels[MyIndex]);
    2.  
     
    cristo likes this.
  5. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Thanks for your time and insight.
     
  6. T5Shared

    T5Shared

    Joined:
    Oct 19, 2018
    Posts:
    152
    Nope, MyIndex is already an index from the list. jvo3dc was correct.