Generate random position within object

Generate random position within object

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.

Solutions/Answers:

Answer 1:

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),
                                 gameObject.transform.position.y,
                                 Random.Range (minZ, -minZ));
    return newVec;
}

Answer 2:

http://docs.unity3d.com/ScriptReference/Random-insideUnitSphere.html

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).

References