i want to spawn objects in random manner from the certain spawn area, like a container
of some sort…for example i would make a box and i want to spawn something there but position is random but inside that box…how would i do that? thanks!
you can use a mix of its position, and its scale, to determine the inner space of the box, then to make the spawn use the GameObject.Instantiate, on time intervals of your choice,
also to avoid 2 object spawning on the same position, check if the space is available
A box is defined by its center and its size (i.e. a distance from its minimum position and its maximum position on every axis).
Let’s assume you know these positions and that the box is AA (axis-aligned)
You can just do a method that looks like:
public Vector3 GetSpawnPosition()
{
float t = Random.value;
return Vector3.Lerp(minPosition, maxPosition, t);
}
Now for the general case and for convenience, you can use add a BoxCollider to a GameObject, configure it then access its extents (vector from center to maximum position, basically box size/2) directly:
public Vector3 GetSpawnPosition()
{
BoxCollider box = GetComponent<BoxCollider>();
// Get a random local position
float t = Random.value;
Vector3 localPosition = Vector3.Lerp(box.center-box.extents, box.center+box.extents, t);
// Return the world position
return this.transform.TransformPoint( localPosition );
}