I have a plane in Unity in 3D project, and I want to get its boundaries so I can use them in random function for getting Vector3 coordinates. Currently I am trying like this

GameObject ground;

void Start () {
        ground = GameObject.Find("Ground");
        moveAreaX = ground.GetComponent<Renderer>().bounds.size.x;
        moveAreaZ = ground.GetComponent<Renderer>().bounds.size.z;
        Debug.Log ("X Area: " + moveAreaX + ", Z Area: " + moveAreaZ);

void GetRandomTargetCoords() {
        targetCoordsX = Random.Range(0f, moveAreaX);
        targetCoordsZ = Random.Range(0f, moveAreaZ);
        targetCoords = new Vector3(targetCoordsX, 1.1f, targetCoordsZ);


And in the console I am getting this:

X Area: 108.5801, Z Area: 108.5801

The problem is the units provided by this bounds.size are not equal to the game object's Transform position's units, and so the game object gets out of the Plane's boundaries.

How can I make it have the same units for measurements?

  • \$\begingroup\$ Why are you comparing size with position? \$\endgroup\$ – Adrian Krupa Jul 14 '15 at 22:32
  • \$\begingroup\$ dont know, thats exactly what I am trying to figure out, a way to get the plane's coordinates based on its size \$\endgroup\$ – Borislav Jul 15 '15 at 6:15

If i understand correctly, you want to put a random target on the plane. However, your plane bounds.size are the "sides" of the plane, and do not start at the center. What you want to do is something like this:

float scale = 0.1f;
float moveAreaX = gameObject.GetComponent<Renderer>().bounds.size.x / 2;
float moveAreaZ = gameObject.GetComponent<Renderer>().bounds.size.z / 2;
Vector3 center = gameObject.GetComponent<Renderer>().bounds.center;
targetCoordsX = center.x + Random.Range(-moveAreaX*scale, moveAreaX*scale);
targetCoordsZ = center.z + Random.Range(-moveAreaZ*scale, moveAreaZ*scale);

You take the center of the plane, and add it the size of the corresponding side divided by 2 since you start at the center. That way you randomize positive and negative "half side". The scale is because the scale of the game is not the same for transform.scale and bounds (but i think that actually depends on your game).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.