- Home /
The question is answered, right answer was accepted
Random numbers generation on Android devices
Hi, I'm trying to generate a map procedurally, I use Random.Range to both select the obstacle and its position (around a point). The problem is that in the editor it works perfectly, but when I open the Android Build the level spawns always the same obstacle. In the debug of the android build the random number is always "0". I Create a map of random obstacles and their positions before instantiating the whole map because I want it to spawn when needed without launching the randoms at runtime. Here's the code I'm using:
public void Trace() {
for (int i = 0; i < 100; i++) {
OrderedDictionary obstaclesMap = new OrderedDictionary();
foreach (Transform child in Tile.transform) {
obstaclesMap.Add(child.name, TraceSingleTile());
}
this.GetComponent<TileGenerator>().UpdateTileDataArchive(obstaclesMap);
}
}
private OrderedDictionary TraceSingleTile() {
OrderedDictionary obstaclesArchive = new OrderedDictionary();
Vector3[] obstacleData = new Vector3[2]; //localPosition, localEulerRotation
int randomNumObstacle = Random.Range(0,obstaclesFilePaths.Count - 1);
obstacleData[0] = new Vector3(Random.Range(-0.125f, 0.125f), 0.0f, Random.Range(-0.125f, 0.125f));
obstacleData[1] = Vector3.zero;
obstaclesArchive.Add(randomNumObstacle, obstacleData);
return obstaclesArchive;
}
The Trace() function is called at Start() by another Component. These two functions should generate a map of random obstacles, in the editor works, in the Android build it only spawns the first obstacle (randomNumObstacle = 0). Any help would be greatly appreciated, it's the first time I try to make an Android build, so I might be missing something.
Answer by Bunny83 · Mar 10, 2018 at 08:06 PM
I never had any problems using Unity's Random class (or even System.Random) on android. However you have a general error in your code. This line:
int randomNumObstacle = Random.Range(0,obstaclesFilePaths.Count - 1);
is wrong. You do not cover the whole possible range. The integer version of Random.Range has the min value inclusive but the max limit exclusive. So you should use
Random.Range(0, obstaclesFilePaths.Count);
However this behaviour does not change between any build target or when testing in the editor.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Serialization is working fine in Unity but not on Android 2 Answers
Saving JSON file in Android,How to save json file in android 0 Answers
Google Advertising ID in Unity3D 2 Answers