Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Game Development

Is it possible to prevent objects from spawning within a specified position or area?

My name is Connor Kent. I'm aiming to create an MMO that will blow people away. If you can't see it by the fact that I'm taking this course, I have very little experience in programming in Unity. Mainly because I'm 13 XD. I thought about the potential of having an object spawner that could spawn objects anywhere except for a certain area. It would be great to have the knowledge required to create such a spawner during the development of my game. If anyone knows how to create something like this, will you please give me the instructions to do so?

Hi Connor,

I don't see why not! Please recall that the FlySpawner.cs script creates fly objects in a random location. Using the fly spawner code as an example:

float badLeftX = 2.0f; float badRightX = 5.0f;

float badCloseZ = 3.0f; float badFarZ = 5.0f;

[code...]

while (totalFlies < totalFlyMinimum) { totalFlies++;

        // ...create random position values for fly
        float positionX = Random.Range(-spawnArea, spawnArea);
        float positionZ = Random.Range(-spawnArea, spawnArea);

        // ADDED CODE
    // Make sure X is a legal value.
    if(positionX >= badLeftX && positionX <= badRightX) {

    // ... set X to closest value
    positionX = Math.Abs(positionX - badLeftX) < Math.Abs(positionX - badRightX
            ? badLeftX
            : badRightX;
    }

    // Make sure Z is a legal value.
    if(positionZ >= badCloseZ && positionZ <= badFarZ) {

    // ... set Z to closest value
    positionZ = Math.Abs(positionZ - badCloseZ) < Math.Abs(positionZ - badFarZ)
            ? badCloseZ
            : badFarZ;
    }
        // END - ADDED CODE

        Vector3 flyPosition = new Vector3(positionX, 2f, positionZ);

        // ...and create the new fly.
        Instantiate(flyPrefab, flyPosition, Quaternion.identity);
    }

-HTH