- Home /
Spawning if there is space
I'm writing a game where the player can spawn various types of objects with different shaped and sized colliders. Is there a good way for me to check if there is space in the world for the object to be spawned so I don't spawn things that gets stuck in other objects?
Answer by aldonaletto · Jul 18, 2013 at 04:40 AM
The easiest and fastest way is to check the available space at some position with a sphere or capsule (rotated to any arbitrary direction) that could fully contain the object: the functions CheckSphere and CheckCapsule execute immediately and return true if something touches the test volume. You could implement this by having two prefabs for each object, one for space test and the other for the actual object: instantiate the test object and, if the space is free, delete it and create the actual object.
If your objects can't be reasonably encapsulated by a sphere or capsule, however, you can create a mesh trigger with the desired shape, wait for the next FixedUpdate and verify whether any OnTriggerEnter event was generated: if none, the place is free and you can instantiate the object. This space test takes some time, since you must wait for the next FixedUpdate. It's ok if you just want to know whether a given location is free, but if you want to draw random positions until a free one is found, this may take an unpredictably long time. Anyway, if you want to have more details about this approach, take a look at this question.
Oops! The link to the question was missing - fixed now.
Your answer
Follow this Question
Related Questions
Random generation of Asteroids 3 Answers
Instantiate Prefab at random 1 Answer
Error: Instantiated Enemies don't get hit 2 Answers
Spawning different random objects at the same position? 2 Answers
Two Objects Touching? 0 Answers