How to find width and height of an gameobject with no renderer?
Hi so I've been developing some code and have encountered an issue. For those familiar to AS3 you'd know that if you have for example:
var _gmCase:MovieClip() = new MovieClip();
var _gm1:MovieClip = new Object1(); //has a width and height of 5
var _gm2:MovieClip = new Object2(); //has w width and height of 5
_gmCase.addChild(_gm1);
_gm1.x =0;
_gmCase.addChild(_gm2);
_gm2.x = _gm1.width + 10;
trace(_gmCase.width); //returns 20. // includes the width and distance between furthest object to the left and furthest object to the right.
What I'm trying to get in unity is access the "_gmCase.width", but its an empty GameObject width "_gm1" and "_gm2" attached as children in the Hierarchy and has no Renderer or any other component of any sort apart from my script which is trying to access its width.
"_gm1" and "_gm2" are prefabs and have Renderers and meshes as well as Colliders attached to them.
Please note that "_gmCase.GetComponent().bounds.size.z;" tells me that there is no Renderer attached to the object.
Anyone know of a way to get the Gameobject's width without any components attached to it?
Answer by Oribow · Apr 10, 2016 at 11:48 PM
OK, if scrambled a script together for you. It only works in 3d through. But it could be changed to 2d.
public static Bounds GetRealSize(GameObject parent)
{
MeshFilter[] childrens = parent.GetComponentsInChildren<MeshFilter>();
Debug.Log(childrens[0].mesh.bounds.size+"*" + childrens[0].transform.localScale+ " / 2 + "+ childrens[0].transform.position);
Vector3 minV = childrens[0].transform.position - MultVect(childrens[0].mesh.bounds.size, childrens[0].transform.localScale) / 2;
Vector3 maxV = childrens[0].transform.position + MultVect(childrens[0].mesh.bounds.size, childrens[0].transform.localScale) / 2;
Debug.Log(maxV);
for (int i = 1; i < childrens.Length; i++)
{
maxV = Vector3.Max(maxV, childrens[i].transform.position + MultVect(childrens[i].mesh.bounds.size, childrens[i].transform.localScale) / 2);
minV = Vector3.Min(minV, childrens[i].transform.position - MultVect(childrens[i].mesh.bounds.size, childrens[i].transform.localScale) / 2);
Debug.Log(maxV);
}
Vector3 v3 = maxV - minV;
return new Bounds(minV + v3 / 2, v3);
}
private static Vector3 MultVect(Vector3 a, Vector3 b)
{
a.x *= b.x;
a.y *= b.y;
a.z *= b.z;
return a;
}
Your answer
Follow this Question
Related Questions
TextureParameter, get width? 0 Answers
Getting width and height of gesture? 1 Answer
Canvas match width or height 1 Answer
How to get 2d camera width & height? 2 Answers
Find the Terrain Width and Height 1 Answer