Let’s say this is a 2D game with 20 levels using C#
How would you code it when you press a button on the main menu it loads random levels (scenes) from 0-20? But it will not repeat numbers.
Thank you.
Let’s say this is a 2D game with 20 levels using C#
How would you code it when you press a button on the main menu it loads random levels (scenes) from 0-20? But it will not repeat numbers.
Thank you.
Stick all the numbers 0 through 19 into a 20-element array. Shuffle the array. Then go through the levels according to the indices within the shuffled array.
It’d be nice if Unity had a built-in shuffle function built in. Nor does the .NET standard library. Fortunately, it’s not too difficulty to code it correctly using something like the Fisher-Yates/Knuth algorithm. I’ve also included it in my (paid) asset Make It Random, because shuffling can be such a useful utility for games. (Edit: It looks like you can probably find open source implementations specifically for Unity by searching GitHub.)
There are several post on here on how to shuffle list using different methods.
You could also create a list, pick a random number from the list and then just remove that number from the list whenever it gets picked.
Or, you could even make a list of strings containing scene names and pick a random index and just remove that index. They will all work pretty well.
One very easy way to do this is this way:
List<int> myNiceNumbers = new List<int>();
for(int i = 0; i < 20; ++i)
{
myNiceNumbers.Add(i);
}
int randomIndex = Random.Range(0, myNiceNumbers.Count);
int randomNumber = myNiceNumbers[randomIndex];
myNiceNumbers.RemoveAt(randomIndex);
Thank you all. Let me give it a try.
Fabian,
I’m trying to do this
public void RandomizedLevel()
{
SceneManager.LoadScene(“level” + myNiceNumbers);
}
But it says “myNiceNumbers does not exist in the current context”. I spent hours trying to fix it without any success.
Do you have any suggestions?
myNiceNumbers is a list that is created as a global and populated in the for loop. When accessing a list you have to use an index, thus the reason he is generating a random number and then getting the value from the list before removing it from the list. If you copy his code, just take note of the list being a global variable and the for loop would need to be used somewhere like a start or awake. But also take note that this list needs to persist through scenes to keep from loading the same one over again.
But at the end of the random number pick, you would do your loadscene using
“level” + randomNumber
I have this so far. But I’m getting an error that says “A field initializer cannot reference the nonstatic field” on myNiceNumbers
Am I missing something?
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class Navigate : MonoBehaviour {
List myNiceNumbers = new List();
void Start()
{
for (int i = 0; i < 20; i++)
{
myNiceNumbers.Add(i);
Debug.Log(“Hello”);
}
}
int randomIndex = Random.Range(0, myNiceNumbers.Count);
int randomNumber = myNiceNumbers[randomIndex];
myNiceNumbers.RemoveAt(randomIndex);
public void RandomizedLevel2()
{
SceneManager.LoadScene(“level” + randomNumber);
}
}
First, you have to put this in a function. You can’t compute stuff in class, only declaration.
Then, Your list “myNiceNumbers” and all his class and gameobject will be deleted as soon as you load another scene unless you specifically ask the associed GameObject to not be destroyed.
But you should use a static list instead.
Cool, the random functions seem to be working. However, RemoveAt doesn’t seem to repond. It keeps looping between levels. I thought once levels removed one by one I get zero level leftover.
As suggested I used something like
void MakeSingleton()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
RemoveAt should works fine.
Are doing this everytime you load a new scene ?
for (int i = 0; i < 20; i++)
{
myNiceNumbers.Add(i);
}
I have this code so far. Please see if anything is wrong. Thank you.
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class Navigate : MonoBehaviour {
public static Navigate instance;
List myNiceNumbers = new List();
void Start()
{
for (int i = 0; i < 4; i++)
{
myNiceNumbers.Add(i);
}
}
public void Testing()
{
int randomIndex = Random.Range(0, myNiceNumbers.Count);
int randomNumber = myNiceNumbers[randomIndex];
myNiceNumbers.RemoveAt(randomIndex);
Debug.Log(randomNumber);
SceneManager.LoadScene(“level” + randomNumber);
}
void Awake()
{
MakeSingleton();
}
void MakeSingleton()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
Have you a GameObject with Navigate attached on every scenes you load ?
If so, instance is changing everytime you load a new scene pointing to a new Navigate script.
how can i shuffle this i dont know how to code im only using unity in 2days…
i want to random my questionss… my quiz game is multiple choice with a star reward system
i dont know how to use the shuffle…and when i try that i always get error!!
public static void Shuffle (this T[ ] array) // always error i dont know why this is error
{
int n = array.Length;
while (n > 1)
{
int k = Random.Range(0, n–);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class resonder : MonoBehaviour {
private int idTema;
public Text question;
public Text ChoiceA;
public Text ChoiceB;
public Text ChoiceC;
public Text ChoiceD;
public Text infoanswer;
public string[ ] questions;
public string[ ] alternativeA;
public string[ ] alternativeB; /// holds the choice A - D and hold the (“correct”) answer
public string[ ] alternativeC;
public string[ ] alternativeD;
public string[ ] correct;
private int idQuestion;
private float points;
private float fact;
private float media;
private int FEResult;
// Use this for initialization
void Start () {
idTema = PlayerPrefs.GetInt (“idTema”);
idQuestion = 0;
fact = questions.Length;
question.text = questions [idQuestion];
ChoiceA.text = alternativeA [idQuestion];
ChoiceB.text = alternativeB [idQuestion];
ChoiceC.text = alternativeC [idQuestion];
ChoiceD.text = alternativeD [idQuestion];
infoanswer.text = "Answering " + (idQuestion + 1).ToString () + “of " + fact.ToString () + " questions”;
}
public void answer(string alternative)
{
if (alternative == “A”)
{
if (alternativeA [idQuestion] == correct [idQuestion])
{
points += 1;
}
}
else if (alternative == “B”)
{
if (alternativeB [idQuestion] == correct [idQuestion])
{
points += 1;
}
}
else if (alternative == “C”)
{
if (alternativeC [idQuestion] == correct [idQuestion])
{
points += 1;
}
}
else if (alternative == “D”)
{
if (alternativeD [idQuestion] == correct [idQuestion])
{
points += 1;
}
}
nextQuestion ();
}
void nextQuestion()
{
idQuestion += 1;
if (idQuestion <= (fact-1))
{
question.text = questions [idQuestion];
ChoiceA.text = alternativeA [idQuestion];
ChoiceB.text = alternativeB [idQuestion];
ChoiceC.text = alternativeC [idQuestion];
ChoiceD.text = alternativeD [idQuestion];
infoanswer.text = "Answering " + (idQuestion + 1).ToString () + “of " + fact.ToString () + " questions”;
}
else
{
media = 10 * (points / fact);
FEResult = Mathf.RoundToInt (media);
if(FEResult > PlayerPrefs.GetInt(“FEResult”+idTema.ToString()))
{
PlayerPrefs.SetInt(“FEResult”+idTema.ToString(), FEResult);
PlayerPrefs.SetInt(“points”+idTema.ToString(), (int) points);
}
PlayerPrefs.SetInt(“FEResultTemp”+idTema.ToString(), FEResult);
PlayerPrefs.SetInt(“pointsTemp”+idTema.ToString(), (int) points);
Application.LoadLevel(“FEResult”);
}
}
}
hello I want to ask I use random scenes like the one above, then I add the reload function, when reloaded the scene that runs only one, which error is there?