- Home /
Instantiating prefab at random and unoccupied locations
So apparently taking a year off meant losing the little bit of programming knowledge I gained in college. I'm trying to make it so that my prefab cubes (called snooters because I'm a dweeb) are spawned at random locations, but don't ever occupy the same spot. So far it works well for the first ~10 or so, but occasionally I'll get either a "stack overflow exception" error or multiple cubes pop up at once.
public GameObject snootInstance;
public List <string> snootsInGame = new List<string>();
public void chooseLocation()
{
//choose x spot
int xSpot = Random.Range(-8, 8);
//choose y spot
int ySpot = Random.Range(-2, 4);
//make them checkable coordinates
string spotLocation = xSpot + ", " + ySpot;
//check those coordinates
decideToSpawn(spotLocation, xSpot, ySpot);
}
void decideToSpawn(string spotToCheck, int xSpot, int ySpot)
{
if (snootsInGame.Contains(spotToCheck) == true) //if the list has the coordinates already, go back and get new ones
{
chooseLocation();
}
else //if not, then go ahead to spawning
{
spawnNew(spotToCheck, xSpot, ySpot);
}
}
void spawnNew(string spotToAdd, int xLocation, int yLocation)
{
snootsInGame.Add(spotToAdd); //add the coordinates to the list
Instantiate(snootInstance, new Vector3(xLocation, yLocation, 0), Quaternion.identity); //make the cube
print("spawned at " + xLocation + ", " + yLocation); //tell console where it spawned
Answer by Captain_Pineapple · May 28, 2018 at 08:25 AM
Hey there,
well since you wrote code that can run in a circle there is one case that you get a stack overflow. That is when you hit an already occupied Spot again and again until the stack is full.
Even though recursive functions can be nice sometimes i'd advice against it in this instance and propose the following:
Implement a 2D-Array with all the possible "Spots". Fill it with some markers like "0" for free and "1" for occupied. Or make it boolean, or a custom type. You can be creative here. Then instead of choosing a random position you get yourself a random number, let's call it P, between 0 and your (maxGridSizeX * maxGridSizeY - snootsInGame.Count) Then you iterate your 2D-Array until you reach the Pth empty position. This is now your random position to set your new Snoot to. This will eliminate the possibility of getting stuck in an endless loop.
Hope this helps. In case you need some coding help let me know.
Right! That is a much more elegant solution. I remembered my professors telling my not to have functions circle like that but couldn't come up with an alternative; I completely forgot I could just build a grid. Thanks so much!
Your answer
Follow this Question
Related Questions
Checking if object intersects? 1 Answer
Setting the parent of a transform which resides in a prefab error 1 Answer
InvokeRepeating for random ball spawn 1 Answer
I need help with rotation 2 Answers