Calculate objects' mass based on density and volume

Hello,
I’m trying to calculate objects’ masses based on density and volume.

Imagine I have a Box2DSprite and it is 1,1 (x,y), I could use mass=densityBox2D.localScale.xBox2D.localScale.y and calculate it.

I want to order the boxes in a GameObject called Boxes and then they are parents.
I want to calculate each box weight/mass individually based on the formula and then apply to the objects!

How could I do this?

Code in JS:

#pragma strict

var Density:float=1000; 

function Start(){
var Rigidbodies=gameObject.GetComponentsInChildren(Rigidbody2D);
var Transforms=gameObject.GetComponentsInChildren(Transform);

for (var Tfm : Transform in Transforms)
for (var Rb : Rigidbody2D in Rigidbodies)
Rb.mass=Density*Tfm.localScale.x*Tfm.localScale.y;
}

I think I see your problem. You’re looping through each transform, and at each transform you are looping through every rigidbody and settting all rigidbodies with whatever mass you calculated for that rigidbody, so they will all end up with whatever you calculated for the last one.

Instead, try something like this (not good at javascript sorry for errors)

//all child transforms
var children = gameObject.GetComponentsInChildren(Transform);

for (var child : Transform in children){
 float calculatedMass = child.localScale.x*child.localScale.y*density;
 //not sure you can get a rigidbody from transform like that. 
 //otherwise I guess child.gameObject.rigidbody is the way to access it?
 Rigidbody body = child.rigidbody;
 if(body) body.mass = calculatedMass;
 else Debug.LogError("This object has no rigidbody on it!");    
}