Snippets

Olivier Giniaux Blender to Unity Definitive Orientation Fix

Created by Olivier Giniaux
using UnityEngine;
using UnityEditor;
using Ogxd;

public class BlenderPostProcessor : AssetPostprocessor {

    void OnPostprocessModel(GameObject gameObject) {
        gameObject.transform.localEulerAngles = Vector3.zero;
        gameObject.transform.localScale = Vector3.one;
        var gameObjects = GetChildrenRecursive(gameObject);
        gameObjects.Add(gameObject);
        foreach (GameObject current in gameObjects) {
            processMesh(current);
            setMaterial(current);
        }
    }

    private void setMaterial(GameObject gameObject) {
        Material[] materials = GetMaterials(gameObject);
        for (int i = 0; i < materials.Length; i++) {
            materials[i] = Resources.Load<Material>("VertexColorStandard");
        }
        gameObject.GetComponent<Renderer>().sharedMaterials = materials;
    }

    private void processMesh(GameObject gameObject) {
        Mesh mesh = GetMesh(gameObject);
        if (!mesh)
            return;
        // Invert Y and Z
        var vertices = mesh.vertices;
        for (int i = 0; i < vertices.Length; i++) {
            vertices[i] = new Vector3(vertices[i].x, vertices[i].z, vertices[i].y);
        }
        mesh.vertices = vertices;
        // Invert 2rd indice with 3rd
        var indices = mesh.triangles;
        for (int i = 0; i < indices.Length; i += 3) {
            int swap = indices[i + 2];
            indices[i + 2] = indices[i + 1];
            indices[i + 1] = swap;
        }
        mesh.triangles = indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        mesh.RecalculateTangents();
    }
    
    public static Mesh GetMesh(GameObject gameObject)
    {
        MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
        if (meshFilter)
            return meshFilter.sharedMesh;
        else
            return null;
    }

    public static Material[] GetMaterials(GameObject gameObject)
    {
        Renderer renderer = gameObject.GetComponent<Renderer>();
        if (renderer)
            return renderer.sharedMaterials;
        else
            return new Material[0];
    }

    public static List<GameObject> GetChildrenRecursive(GameObject gameObject)
    {
        List<GameObject> gameObjects = new List<GameObject>();
        Queue<GameObject> queue = new Queue<GameObject>();
        queue.Enqueue(gameObject);
        while (queue.Count != 0) {
            GameObject current = queue.Dequeue();
            foreach (Transform transform in current.transform) {
                queue.Enqueue(transform.gameObject);
                gameObjects.Add(transform.gameObject);
            }
        }
        return gameObjects;
    }
}

Comments (0)