I’ve been racking my head over this problem for a few days now. I need to make a user friendly script that resizes game objects that are imported. This means that “Userfriendly” they need to attach the script, and it works everytime.
But there will be no standardization for where meshfilters are in the gameobjects heirarchy.
Example:
3D model of a Sofa, and 3D model of bicycle were imported to Unity.
- 3D Sofa Model has 5 child objects each with a meshfilter. 1 for each seat cushion and the base of the Sofa… etc
- The Bicycle Model has a Meshfilter on the parent object, and then several children within children down to the last nut.
The 3d model could have multiple children under the children, maybe the filter is on the game object itself with no children at all!
Anyways, this is what I have. The issue is that because the bounds are on children objects, the transforms aren’t aligning with the sister/brother objects. Finally, an iterator would need to be added to run this script on the Game Object, and then all children, etc.
using UnityEngine;
using System.Collections;
public class ResizeAsset : MonoBehaviour {
void Awake()
{
ResizeMesh(GetComponentsInChildren<MeshFilter>());
}
void ResizeMesh(MeshFilter[] collection)
{
foreach (MeshFilter mf in collection)
{
mf.GetComponent<MeshFilter>();
Transform tf = mf.GetComponent<Transform>();
if (mf == null || tf == null)
{
Debug.Log("Your Transform or or Mesh has returned null. Consult Documentation XYZ");
return;
}
Mesh mesh = mf.sharedMesh;
Bounds bounds = mf.GetComponent<Renderer>().bounds;
float size = bounds.size.x;
if (size < bounds.size.y)
{
size = bounds.size.y;
}
if (size < bounds.size.z)
{
size = bounds.size.z;
}
if (Mathf.Abs(1.0f - size) < 0.01f)
{
Debug.Log("Already unit size");
return;
}
float scale = 1.0f / size;
Vector3[] verts = mesh.vertices;
for (int i = 0; i < verts.Length; i++)
{
verts[i] = verts[i] * scale;
}
tf.position = new Vector3(tf.position.x * scale, tf.position.y * scale, tf.position.z);
mesh.vertices = verts;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
}
}
}
Even with this code the transform isn’t changing properly. I think it has to do with the fact the bounds size on each childobject is different, so the repositioning since I’m using scale is different.
If anyone has any idea how I should proceed that would be great.