Random number in range, but not in a smaller range.

Hello, I wrote a script that spawn an enemy in a random place in range, but not in a smaller range, The script work theoretically, but practically it just get stuck in a loop, any way to fix that?

    void spawnEnemy(int amount) {
        for (int i = 0; i < amount; i++)
        {
            Position = new Vector3(Random.Range(MinSpawn, MaxSpawn), Random.Range(MinSpawn, MaxSpawn), 0);
            if (Position.x >= -4 && Position.x <= 4 || Position.y >= -4 && Position.y <= 4) {
                spawnEnemy(amount);
            } else {
                Instantiate(EnemyPrefab, Position, Quaternion.identity);
                amount--;
            }
        }
    }

I want it to spawn in the green area, but not in the red area

Yes! It is called “debugging.”

But first, do yourself a favor and unroll all that massive blob of code.

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

ALSO: you are using recursion. Do you realize this? This is not a problem that gains any advantage by a recursive solution. Just iterate and qualify points. If you don’t know how to debug yet, I suggest staying away from recursion.

Once your code is readable by mere humans, time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

You’re calling SpawnEnemy() from within SpawnEnemy(). That’s called recursion. Recursion needs an end-state check or it will try to loop forever. You’re decrementing the amount, but never checking if it reaches zero.

In each level of the recursion, you’re doing a for loop. That’s called iteration.

You should choose either iteration or recursion, not both. I think for your stated goals, iteration is the proper thing.

As Kurt suggested, break this up more simply. My suggestion would be something structured like this. I am not giving full code, I am giving pseudocode that gets you started, you have to fill in the blanks:

void SpawnEnemies(int amount)
{
    // loop amount times, calling SpawnOneEnemy() ...
}

void SpawnOneEnemy()
{
    // loop until successful or too many retries
    int tries = 10;
    while (tries > 0)
    {
        tries--;

        // pick a random point in area
        var point = ...;
        if (IsPointInsideArea( point, coordinatesOfGreenArea ) &&
            !IsPointInsideArea( point, coordinatesOfRedArea ))
        {
            // actually spawn
            return;
        }
    }
    // didn't spawn anything, no good point found in all those tries
}

bool IsPointInsideArea( point, coordinatesOfMyArea )
{
    // return true if point is inside
}

Is there a way to promise it will spawn the requested amount of enemies and not risking overloading? Maybe Is there a way to get a random number from like 1 to 10 except 4 to 7?

Usually you just pick a huge number like 1000 or 10000 that is still small to a computer, and loop that many times.

Loop 10000 times:

  • pick a random spot
  • qualify it and if it is good:
    —> spawn the item
    —> count down your “amount”
    —> if zero return
  • otherwise keep looping

Yes, it is possible to spawn fewer than you request as obviously it is just a dartboard.

If you absolutely must spawn precisely that many then make yourself a list of known good spots, shuffle them and pick the first N spots.

You’re welcome to see some similar spawning strategies in my MakeGeo project. Search up “spawn” in the project.

MakeGeo is presently hosted at these locations:

https://bitbucket.org/kurtdekker/makegeo

Thank you, I thought the loop should be way smaller. That makes way more sense

Imagine yourself picking a random ball from a bag.

  1. Balls are labeled 1…10. You pick a ball in the invalid range 4…7, what do you do? You get it back and try again.
int ball;

do {
  ball = Random.Range(0, 10) + 1;
} while(ball >= 4 && ball <= 7)

Debug.Log(ball);

Pros:
You can freely adjust the range of the invalid results. If you suddenly decide to remove 10, you can do
ball = Random.Range(0, 9) + 1; or while(ball >= 4 && ball <= 7 || ball == 10)

Cons:
This code is prone to wasting time on repeats. Also you can mess up and your loop can become infinite. The invalid choices are ‘hardcoded’, meaning they are set into the method itself.

  1. In this scenario the bag doesn’t contain all the labels, instead it contains only valid options, but these aren’t labeled properly. So the balls are 1, 2, 3, 4, 5, 6. But you then interpret labels 4, 5, 6 as 8, 9, 10.
int ball = Random.Range(0, 6) + 1; // 6 is number of valid options
if(ball >= 4) ball += 4; // 4 -> 8, 5 -> 9, 6 -> 10

Debug.Log(ball);

Pros:
Easy to make and no repeated attempts.

Cons:
Hard to read and maintain if you need to change something later. Relies on so-called magic numbers 6 and 4, which should be explained with comments.

  1. The bag contains only the valid labels. So the balls are labeled as such 1, 2, 3, 8, 9, 10.
int[] valid = new int[] { 1, 2, 3, 8, 9, 10 };
int index = Random.Range(0, valid.Length);
int ball = valid[index];

Debug.Log(ball);

Pros:
No repeated attempts, no magic numbers (such as 6 and 4 in the previous example). Also easy to read and very friendly to all kinds of changes. Hardcoded values can be produced somewhere else, so it’s not a problem anymore.

Cons:
Has to allocate a data array in advance.

To elaborate this further, you can easily build general-purpose methods from examples #1 and #3

Solution #1

int pickRandom(int start, int end, Func<int, bool> condition) {
  Debug.Assert(start <= end, "end is less than start");
  int result;
  do {
    result = Random.Range(start, end + 1);
  } while(condition is not null && condition(result))
  return result;
}

Usage

int ball = pickRandomLabel(1, 10, (i) => (i <= 4 && i >= 7) );
Debug.Log(ball);

-or-

Solution #3

int pickRandom(int[] options)
  => options[Random.Range(0, options.Length)];

Usage

int[] options = new int[] { 1, 2, 3, 8, 9, 10 };
int ball = pickRandom(options);
Debug.Log(ball);

Solution #2 rarely pays off because of how it ad hoc mutates the result, with no apparent meaning, but it may useful in specific tight algorithms so it’s worth learning.