2

I'm writing a script for an Object in Unity3D.

I want to get the volume of my object.

rigidBody = GetComponent<Rigidbody>();

I'm looking in the documentation at the attributes contained in Rigidbody but I don't see anything I can use.

I tried using bounds but I found that rotation of an object changed those values even without size changing:

int getSize(Vector3 bounds)
{
    float size = bounds[0] * bounds[1] * bounds[2] * 1000;
    Debug.Log("size value = " + (int)size);
    return (int)size;
}

What properties can I use to calculate the volume of an object?

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • Posting as a comment because it's untested, but I know that density and mass are properties you can get. You can calculate volume by dividing your mass by your density. – Logarr Jul 27 '19 at 21:13
  • @Logarr I see the mass attribute but I don't see density, is there a default value for density? – Philip Kirkbride Jul 27 '19 at 21:26

1 Answers1

2

The math is explained here.

In C# for convencience:

float SignedVolumeOfTriangle(Vector3 p1, Vector3 p2, Vector3 p3)
{
    float v321 = p3.x * p2.y * p1.z;
    float v231 = p2.x * p3.y * p1.z;
    float v312 = p3.x * p1.y * p2.z;
    float v132 = p1.x * p3.y * p2.z;
    float v213 = p2.x * p1.y * p3.z;
    float v123 = p1.x * p2.y * p3.z;
    return (1.0f / 6.0f) * (-v321 + v231 + v312 - v132 - v213 + v123);
}

float VolumeOfMesh(Mesh mesh)
{
    float volume = 0;
    Vector3[] vertices = mesh.vertices;
    int[] triangles = mesh.triangles;
    for (int i = 0; i < mesh.triangles.Length; i += 3)
    {
        Vector3 p1 = vertices[triangles[i + 0]];
        Vector3 p2 = vertices[triangles[i + 1]];
        Vector3 p3 = vertices[triangles[i + 2]];
        volume += SignedVolumeOfTriangle(p1, p2, p3);
    }
    return Mathf.Abs(volume);
}

Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
Debug.Log(VolumeOfMesh(mesh));
Iggy
  • 4,767
  • 5
  • 23
  • 34
  • I'm running this code but the output remains the same even as the object shrinks. I have my script attached to the object should `GetComponent().sharedMesh` be returning the mesh of the object I attached the script to? – Philip Kirkbride Jul 27 '19 at 21:46
  • Yeah, it would give you the first mesh it finds on the current object. Now that you mention it. You're scaling the object, but the mesh will stay the same as it's in object space, you can probably scale the volume down by `transform.localScale.x`. Not sure if that will give you the true volume. May need to look into the TRS matrix. – Iggy Jul 27 '19 at 21:53
  • thanks that seems to be what I need, the `transform.localScale.x`. – Philip Kirkbride Jul 27 '19 at 22:11