# Randomly instantiate avoiding overlapping in Unity 5

I'm starting a 2D game where I want all the letters A-Z displayed in a random position and, then, the player collects them all in the correct order. I need to randomly instantiate the letters without overlapping. I use C#.

• What did you try? – Alexandre Vaillancourt Jul 16 '16 at 22:05
• I have thought using an array of possible points to instantiate, but I'm kinda newbie on C# – Keoni Jul 16 '16 at 22:14
• So you want us to write your code for you? How will you learn? – Alexandre Vaillancourt Jul 16 '16 at 22:15
• I did not ask for all the code. Something to start with would also be of some help. Thank you anyway. – Keoni Jul 16 '16 at 22:25

## Separated grid

Randomly pick a box that hasn't been chosen yet, then randomly place the item within that grid space. The space between the boxes is enough so that items placed on the edge of a box doesn't intersect with an item placed on the edge of an adjacent box. This can be implemented pretty simply with a list and a bit of math.

## Try, and try again

Randomly place the items, after each placement, check for overlap. If there's an overlap, remove the item and choose a new random location until you've found one that doesn't overlap.

## Try, and move

Randomly place the items, after each placement, check for overlap. If there's an overlap, move the new item away from the existing item until it fits or goes out of bounds. If it goes out of bounds, try placing it again.

## Use physics

Randomly generate the objects with physics and gravity. Allowing them to drop into a container, letting the physics system keep track of keeping them separated based on their colliders.

## Uniform and wiggle

Place all the items uniformly on a grid, in random order, then change their positions by a small random amount, ensuring that doing so doesn't cause them to overlap.

It's not the cleanest method, but an easy starting point would be to make a char[] array filled with all the letter, then randomize the order. Create an array of Vector3 points that can contain the letters (obviously at least 26 points). Then instantiate an object containing the letter from the next char[] value randomly to one of the Vector3 points. That might be an object that is given the next char[] value as a char which works with a script on the object to display that letter.

• You could also use a Queue<char> or Stack<char>. Then you can do Stack.Pop() or something similar to ensure your collection of char items removes the one that was just used. – Jesse Williams Jul 18 '16 at 15:15
• Thank you. That sounds good to check which letters were spawned, but not to position them randomly nor doing it where another one is. – Keoni Jul 20 '16 at 21:36