I have a plate object which is generated somehow (I don't care how), now I want to put another object within this object on random position. Lets say that I want to put random trees on this plate. How can I achieve this in Unity. I had read for bounds but I don't know how to use it to generate position for the tree.


This way you would get a random position on your plane. To get the correct size of your plane you need to get the MeshFilter which gives you the right bounds of the object.

public Vector3 GetARandomTreePos(){

    Mesh planeMesh = gameObject.GetComponent<MeshFilter>().mesh;
    Bounds bounds = planeMesh.bounds;

    float minX = gameObject.transform.position.x - gameObject.transform.localScale.x * bounds.size.x * 0.5f;
    float minZ = gameObject.transform.position.z - gameObject.transform.localScale.z * bounds.size.z * 0.5f;

    Vector3 newVec = new Vector3(Random.Range (minX, -minX),
                                 Random.Range (minZ, -minZ));
    return newVec;


If you need something more complicated than a sphere, or box, you will end up creating your own randomize logic by hand.

You could set values in the inspector for example, bound values.

You could set up possible colliders, then randomize the position, and test it against these colliders(if the position is inside one of these).


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.