As many others have said already, this is surprisingly complex to solve. A possible way to make it easier to solve is to break the mesh into its core components, triangles.
-
Create a class that will old 3 points on a triangle in vector3.
-
Get all the triangles within the mesh. They are pairs of 3 integers that represent index of the vertex they connect to.
-
Get the vertexes that the triangles point to and put it in the class.
-
You should now have a list of classes that represents triangles. Pick a random one.
-
Pick a random point within that triangle.
-
Profit.?
Edit: Have a look at this answer, it should help out too Am I inside a volume? (without colliders) - Unity Answers
Here is an example. Please note that this doesn’t actually give a point on the triangle, but should give a rough idea on what to do.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PointInTriangle : MonoBehaviour {
public Vector3 GetRandomPoint(Mesh m)
{
//Prepare a list of all triangles
List<Triangle> triangles = new List<Triangle>();
//Iterate over each triangle
for(int i = 0; i < m.triangles.Length; i += 3)
{
//Get the index of the vertices
int a = m.triangles*;*
int b = m.triangles[i + 1];
int c = m.triangles[i + 2];
//Create the triangle class
Triangle t = new Triangle();
//Get the actual vertecies
t.vertexA = m.vertices[a];
t.vertexB = m.vertices**;**
t.vertexC = m.vertices
```c
**;
//Add the triangle to the list
triangles.Add(t);
}
//Make sure we have actually found triangles
if (triangles.Count == 0)
return Vector3.zero;
//Pick a random triangle
Triangle t = triangles[Random.Range(0, triangles.Count)];
//Get a random point within the triangle
return t.GetRandomPoint();
}
}
public class Triangle
{
public Vector3 vertexA, vertexB, vertexC;
public Vector3 GetRandomPoint()
{
//This happens to be the easiest to calculate
Vector3 min = GetMinPoint();
Vector3 max = GetMaxPoint();
//Give a random point.
//NOTE! This will not return a point on the triangle, but instead just a random point within the area the triangle makes up.
//You will have to find more complicated algorythms to detect a random point on 3D triangles.
return new Vector3(Random.Range(min.x, max.x), Random.Range(min.y, max.y), Random.Range(min.z, max.z));
}
Vector3 GetMinPoint()
{
Vector3 point = new Vector3();
point.x = Mathf.Min(vertexA.x, vertexB.x, vertexC.x);
point.y = Mathf.Min(vertexA.y, vertexB.y, vertexC.y);
point.z = Mathf.Min(vertexA.z, vertexB.z, vertexC.z);
return point;
}
Vector3 GetMaxPoint()
{
Vector3 point = new Vector3();
point.x = Mathf.Max(vertexA.x, vertexB.x, vertexC.x);
point.y = Mathf.Max(vertexA.y, vertexB.y, vertexC.y);
point.z = Mathf.Max(vertexA.z, vertexB.z, vertexC.z);
return point;
}
}**</em>
```