- Home /
Random int generation between two intervals
I'm making a game with procedural generation for each level. At the beginning I want to create a random number of game objects(done) at a random distance(sorta done). So right now I have a random number of game objects being formed at a distance (with Random.Range(1000, 6000)). But I don't want it to be just positive, for example, generate a number between -6000 and 6000 excluding anything smaller than 1000 and greater than -1000. After looking around the only way that came to me was using a random number between 1 and 4 where the number would be the quadrant it'd be in and then use a switch loop for each possible case.
switch (wormhole[curWormholeGen]){
case 1:
switch(genQuadrant){
case 1:
Instantiate (wormholeType1, transform.position + new Vector3(Random.Range(minX, maxX), 0, Random.Range (minZ,maxZ)), transform.rotation);
break;
case 2:
Instantiate (wormholeType1, transform.position + new Vector3(-Random.Range(minX, maxX), 0, Random.Range (minZ,maxZ)), transform.rotation);
break;
case 3:
Instantiate (wormholeType1, transform.position + new Vector3(-Random.Range(minX, maxX), 0, -Random.Range (minZ,maxZ)), transform.rotation);
break;
case 4:
Instantiate (wormholeType1, transform.position + new Vector3(Random.Range(minX, maxX), 0, -Random.Range (minZ,maxZ)), transform.rotation);
break;
}
this is just a snippet from a part of the code. There's also a random length for the array etc... There must be a more effective way than this right?
Thanks for the help,
Troponeme
Answer by rutter · Nov 13, 2013 at 01:09 AM
The bad news is that there's no built-in function for that. The good news is that it's very easy to write your own.
Something like this will do the trick for a single integer:
//number will have absolute value between min, max
//number has 50% chance of being pos/neg
public static int AbsRange(int min, int max) {
int i = Random.Range(min, max);
return Random.value < 0.5f ? i : -i;
}
If you wanted, you could write similar functions for floats, vectors, or whatever other types you might need.
Thanks, ins$$anonymous$$d of changing it to create vectors I changed it for floats and created a new vector with a generated number each time. Probably would have saved me time overall to just go with vectors ins$$anonymous$$d of floats but oh well! It works!
Your answer
Follow this Question
Related Questions
instantiation at interval times 3 Answers
Making enemies jump at random (c#) 2 Answers
Request: Advice on delving into "Procedurally Generated Content(PGC)". C# 2D Unity 2 Answers
Procedural Generation 2 Answers
How do i spawn a square in random position within an area but only at certain x and y intervals? 1 Answer