FYI I'm quite new with prograaming and c#. Sorry if this seem idioticly simple question.
I have a bit of difficulty to explain what I want to do. So basically, there is array/list of numbers. The number would be picked by using Random.Range(). Each number would have their own action they would active. For example, number 1 would boot up scene1, number 2 would boot up scene2 and so on. How do you assign this randomly chosen number to a certain action?
I don't even know how to put this in code (use array/string?), but the basic idea would probably look something like this:
int randomNumber = Random.Range(1, 10);
randomNumber[1] = SceneManager.LoadScene(Level1);
randomNumber[2] = SceneManager.LoadScene(Level2);
...
CodePudding user response:
Note that this answer is not exact ;)
The upper limit of Random.Range(int,int)
is exclusive so
Random.Range(0, 10)
will never return 10
but values between 0
and 9
.
Even simplier actually would be to store all the scenes in an array e.g.
public List<string> scenes = new List<string>();
and then use
var randomIndex = Random.Range(0, scene.Length);
SceneManager.LoadScene(scenes[randomIndex]);
there is no need for a long and undynamic if-else
or switch-case
. The array/list can be fully dynamically adjusted in the Inspector or even on runtime without having to add more cases.
CodePudding user response:
The easiest way of going about this is:
int randomNumber = Random.Range(1, 10);
if(randomNumber == 1) {
// Load Scene 1
} else if (randomNumber == 2) {
// Load Scene 2
}
EDIT:
You don't assign the random number in this case. You check if the random number is a specific number. You can check if numbers are equal using ==
.
The random number has a value between 1 and 9 and this number is random everytime you run the program.
If you want to do it more dynamically you can look at the answer from @derHugo. Depends on how you use it and how many if-else statements you have to write.