- Home /
Random object spawn?
Hello, how would I spawn a series of objects (enemies or collectables) at pre-set points? For example: If I set up 100 spawn points and there are 25 collectables, how would I do that? Also, how would I just make it so that the objects spawn anywhere within a boundary set in unity (like enemies spawning anywhere in a cube space that is set as the level boundary and not just at set points)
Answer by Jesse Anders · Nov 06, 2010 at 07:52 PM
If you have a set of specific spawn points, one approach would be the following. Store the spawn points in a suitable container, such as an array. Then, store a separate, dynamic list of 'free spawn point indices' (the generic List container would be a good choice for this).
The 'free index' list should initially contain the indices of all the spawn points (0-99 in your example). Every time you want to spawn an item, select an element from the 'free index' list randomly (e.g. using Random.Range()). Spawn an object at the spawn point, and then remove that index from the list. If objects can continue to spawn over the course of the game, you'll probably also need to add spawn point indices to the 'free index' list once the spawn point becomes available again. (Note that this approach is based on the assumption that you only want one object at any one spawn point at any one time.)
For the second question, you can just use Random.Range() to assign a random value in the appropriate range to the x, y, and z elements of the position of the new object.
Your answer
Follow this Question
Related Questions
Placing trees randomly across a large terrain 1 Answer
How do I randomly create 2 objects, each with a different shape and color? 1 Answer
How do I make a game object spawn several times in semi-random locations? 1 Answer
Make Objects spawn within different screen sizes 0 Answers
Generating pickups randomly 3 Answers