# Instantiate Object at any Random Point within a Box Collider 2D

Discussion in 'Scripting' started by AnimalMan, Nov 10, 2018.

1. ### AnimalMan

Joined:
Apr 1, 2018
Posts:
77
Sounds simple, Right?

public GameObject SpawnItem;
public Transform 2DColliderTransform;
public Float RandomPositionX;
public float RandomPosition Y;

RandomPositionX = Random.range(-5,5)
RandomPositionY = Random.range(-5,5)

Lets go from here. Can anybody help?

2. ### Reeii

Joined:
Feb 5, 2016
Posts:
88
If you want to instantiate the object somewhere within the collider, you need to reference it.
Code (CSharp):
1. public BoxCollider2D collider;
Then you can calculate its edges by adding the its offset to it's transform position and then the size / 2:
Code (CSharp):
1. public void InstantiateObject() {
2.     Vector2 colliderPos = collider.transform.position + collider.offset;
3.     float randomPosX = Random.Range(colliderPos.x - collider.size.x / 2, colliderPos.x + collider.size.x / 2);
4.     float randomPosY = Random.Range(colliderPos.y - collider.size.y / 2, colliderPos.y + collider.size.y / 2);
5.
6.     GameObject instantiatedObject = Instantiate(SpawnItem, new Vector3(randomPosX, randomPosY), Quaternion.identity);
7. }
PS: Remember to use code tags!

3. ### santiagolopezpereyra

Joined:
Feb 21, 2018
Posts:
91
You can get a random position within an area using

Code (CSharp):
1.
2. Random.insideUnitSphere
3.
This returns a random point inside a sphere of radius 1. To make the radius be the same size as your box collider, just say

Code (CSharp):
1. Random.insideUnitSphere *  boxColliderSize
where boxColliderSize is an integer or a float.

At last, the previous code returns a random point within an area the same size of your collider, but its center is at zero. To let the center of this area be the same as your collider, simply say

Code (CSharp):
1. transform.position + Random.insideUnitSphere * boxColliderSize
and you are done. This returns a random Vector3 point among an area with the center at your object's transform and the same size as its collider.

Of course you can store it in a variable:

Code (CSharp):
1. Vector3 randomPos = transform.position + Random.insideUnitSphere * boxColliderSize;
Then simply instantiate your object at this new position.

EDIT: How silly of me; you want a 2D area. Simply replace random.insideUnitSphere with random.insideUnitCircle, and you'll have a Vector2 point in 2D.