AssetPostprocessor lets you hook into the import pipeline and run scripts prior or after importing assets.

 private static void InitPostprocessors(string pathName)
 {
     AssetPostprocessingInternal.m_ImportProcessors = new ArrayList();
     foreach (System.Type type in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor)))
     {
         try
         {
             AssetPostprocessor instance = Activator.CreateInstance(type) as AssetPostprocessor;
             instance.assetPath = pathName;
             AssetPostprocessingInternal.m_ImportProcessors.Add((object)instance);
         }
         catch (MissingMethodException ex)
         {
             AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(type);
         }
         catch (Exception ex)
         {
             Debug.LogException(ex);
         }
     }
     AssetPostprocessingInternal.m_ImportProcessors.Sort((IComparer) new AssetPostprocessingInternal.CompareAssetImportPriority());
     AssetPostprocessingInternal.PostprocessStack postprocessStack = new AssetPostprocessingInternal.PostprocessStack();
     postprocessStack.m_ImportProcessors = AssetPostprocessingInternal.m_ImportProcessors;
     if (AssetPostprocessingInternal.m_PostprocessStack == null)
     {
         AssetPostprocessingInternal.m_PostprocessStack = new ArrayList();
     }
     AssetPostprocessingInternal.m_PostprocessStack.Add((object)postprocessStack);
 }
        private static void PostprocessAudio(AudioClip tex, string pathName)
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor target = (AssetPostprocessor)enumerator.Current;
                    object[]           args   = new object[]
                    {
                        tex
                    };
                    AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessAudio", args);
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
        }
 private static void InitPostprocessors(string pathName)
 {
     AssetPostprocessingInternal.m_ImportProcessors = new ArrayList();
     foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor)))
     {
         try
         {
             AssetPostprocessor assetPostprocessor = Activator.CreateInstance(current) as AssetPostprocessor;
             assetPostprocessor.assetPath = pathName;
             AssetPostprocessingInternal.m_ImportProcessors.Add(assetPostprocessor);
         }
         catch (MissingMethodException)
         {
             AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(current);
         }
         catch (Exception exception)
         {
             Debug.LogException(exception);
         }
     }
     AssetPostprocessingInternal.m_ImportProcessors.Sort(new AssetPostprocessingInternal.CompareAssetImportPriority());
     AssetPostprocessingInternal.PostprocessStack postprocessStack = new AssetPostprocessingInternal.PostprocessStack();
     postprocessStack.m_ImportProcessors = AssetPostprocessingInternal.m_ImportProcessors;
     if (AssetPostprocessingInternal.m_PostprocessStack == null)
     {
         AssetPostprocessingInternal.m_PostprocessStack = new ArrayList();
     }
     AssetPostprocessingInternal.m_PostprocessStack.Add(postprocessStack);
 }
        private static void PostprocessGameObjectWithUserProperties(GameObject go, string[] prop_names, object[] prop_values)
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor target = (AssetPostprocessor)enumerator.Current;
                    object[]           args   = new object[]
                    {
                        go,
                        prop_names,
                        prop_values
                    };
                    AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessGameObjectWithUserProperties", args);
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
        }
        private static EditorCurveBinding[] PostprocessGameObjectWithAnimatedUserProperties(GameObject go, EditorCurveBinding[] bindings)
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor target = (AssetPostprocessor)enumerator.Current;
                    object[]           args   = new object[]
                    {
                        go,
                        bindings
                    };
                    AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessGameObjectWithAnimatedUserProperties", args);
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
            return(bindings);
        }
        private static Material ProcessMeshAssignMaterial(Renderer renderer, Material material)
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();
            Material    result;

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor target = (AssetPostprocessor)enumerator.Current;
                    object[]           args   = new object[]
                    {
                        material,
                        renderer
                    };
                    object obj = AttributeHelper.InvokeMemberIfAvailable(target, "OnAssignMaterialModel", args);
                    if (obj as Material)
                    {
                        result = (obj as Material);
                        return(result);
                    }
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
            result = null;
            return(result);
        }
        private static bool ProcessMeshHasAssignMaterial()
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();
            bool        result;

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor assetPostprocessor = (AssetPostprocessor)enumerator.Current;
                    if (assetPostprocessor.GetType().GetMethod("OnAssignMaterialModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null)
                    {
                        result = true;
                        return(result);
                    }
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
            result = false;
            return(result);
        }
            public int Compare(AssetPostprocessor x, AssetPostprocessor y)
            {
                var xi = new AssetPostprocessor.PostprocessorInfo(x.GetType(), x.GetPostprocessOrder());
                var yi = new AssetPostprocessor.PostprocessorInfo(y.GetType(), y.GetPostprocessOrder());

                return(Compare(xi, yi));
            }
        private static void PostprocessAnimation(GameObject root, AnimationClip clip)
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor target = (AssetPostprocessor)enumerator.Current;
                    object[]           args   = new object[]
                    {
                        root,
                        clip
                    };
                    AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessAnimation", args);
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
        }
 public bool ShouldRun(Texture2D texture, AssetPostprocessor postProcessor)
 {
     var textureImporter = (TextureImporter) postProcessor.assetImporter;
     if (textureImporter.DoesSourceTextureHaveAlpha())
         return true;
     return false;
 }
        private static uint[] GetAudioProcessorVersions()
        {
            List <uint> list = new List <uint>();

            foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor)))
            {
                try
                {
                    AssetPostprocessor assetPostprocessor = Activator.CreateInstance(current) as AssetPostprocessor;
                    Type type    = assetPostprocessor.GetType();
                    bool flag    = type.GetMethod("OnPreprocessAudio", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null;
                    bool flag2   = type.GetMethod("OnPostprocessAudio", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null;
                    uint version = assetPostprocessor.GetVersion();
                    if (version != 0u && (flag || flag2))
                    {
                        list.Add(version);
                    }
                }
                catch (MissingMethodException)
                {
                    AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(current);
                }
                catch (Exception exception)
                {
                    Debug.LogException(exception);
                }
            }
            return(list.ToArray());
        }
 private static void PostprocessAssetbundleNameChanged(string assetPAth, string prevoiusAssetBundleName, string newAssetBundleName)
 {
     object[] args = new object[]
     {
         assetPAth,
         prevoiusAssetBundleName,
         newAssetBundleName
     };
     foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor)))
     {
         AssetPostprocessor target = Activator.CreateInstance(current) as AssetPostprocessor;
         AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessAssetbundleNameChanged", args);
     }
 }
        private static void InitPostprocessors(string pathName)
        {
            AssetPostprocessingInternal.m_ImportProcessors = new ArrayList();
            IEnumerator enumerator = AssetPostprocessingInternal.GetCachedAssetPostprocessorClasses().GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    Type type = (Type)enumerator.Current;
                    try
                    {
                        AssetPostprocessor assetPostprocessor = Activator.CreateInstance(type) as AssetPostprocessor;
                        assetPostprocessor.assetPath = pathName;
                        AssetPostprocessingInternal.m_ImportProcessors.Add(assetPostprocessor);
                    }
                    catch (MissingMethodException)
                    {
                        AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(type);
                    }
                    catch (Exception exception)
                    {
                        Debug.LogException(exception);
                    }
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
            AssetPostprocessingInternal.m_ImportProcessors.Sort(new AssetPostprocessingInternal.CompareAssetImportPriority());
            AssetPostprocessingInternal.PostprocessStack postprocessStack = new AssetPostprocessingInternal.PostprocessStack();
            postprocessStack.m_ImportProcessors = AssetPostprocessingInternal.m_ImportProcessors;
            if (AssetPostprocessingInternal.m_PostprocessStack == null)
            {
                AssetPostprocessingInternal.m_PostprocessStack = new ArrayList();
            }
            AssetPostprocessingInternal.m_PostprocessStack.Add(postprocessStack);
        }
        private static void PreprocessTexture(string pathName)
        {
            IEnumerator enumerator = AssetPostprocessingInternal.m_ImportProcessors.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    AssetPostprocessor target = (AssetPostprocessor)enumerator.Current;
                    AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessTexture", null);
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
        }
        private static uint[] GetMeshProcessorVersions()
        {
            List <uint> uintList = new List <uint>();

            foreach (System.Type type1 in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor)))
            {
                try
                {
                    AssetPostprocessor instance = Activator.CreateInstance(type1) as AssetPostprocessor;
                    System.Type        type2    = instance.GetType();
                    bool flag1   = type2.GetMethod("OnPreprocessModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null;
                    bool flag2   = type2.GetMethod("OnProcessMeshAssingModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null;
                    bool flag3   = type2.GetMethod("OnPostprocessModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null;
                    uint version = instance.GetVersion();
                    if ((int)version != 0)
                    {
                        if (!flag1 && !flag2)
                        {
                            if (!flag3)
                            {
                                continue;
                            }
                        }
                        uintList.Add(version);
                    }
                }
                catch (MissingMethodException ex)
                {
                    AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(type1);
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }
            return(uintList.ToArray());
        }
示例#16
0
        /// <summary>
        /// Exports the combined meshes to the folder selected in the Editor Window
        /// </summary>
        /// <param name="realAssetPath">The real asset path to be used by System.IO</param>
        private void ExportMeshes(string realAssetPath)
        {
            string materialsPath = Path.Combine (_exportPath, "Materials");
            char[] invalidChars = Path.GetInvalidFileNameChars ();

            foreach (MeshFilter mf in _hiddenCombinedObject.GetComponentsInChildren<MeshFilter>()) {

                string filename = mf.name;

                foreach (char c in invalidChars) {
                    filename.Replace (c, '_');
                }

                filename += ".obj";
                if (MeshExporter.MeshToFile (mf.sharedMesh, realAssetPath + filename)) {
                    AssetPostprocessor proc = new AssetPostprocessor ();
                    AssetDatabase.Refresh ();

                    //even though it cant get here, should double check that export folder is null or not
                    proc.assetPath = Path.Combine (AssetDatabase.GetAssetPath (_exportFolder), filename);

                    ModelImporter importer = proc.assetImporter as ModelImporter;

                    importer.generateSecondaryUV = _isGeneratingLightmapUVs;
                    importer.generateAnimations = ModelImporterGenerateAnimations.None;
                    importer.optimizeMesh = true;
                    importer.importMaterials = false;

                    AssetDatabase.ImportAsset (Path.Combine (_exportPath, filename), ImportAssetOptions.ForceUpdate);
                    mf.sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath (Path.Combine (_exportPath, filename), typeof(Mesh));

                    AssetDatabase.DeleteAsset (Path.Combine (materialsPath, mf.sharedMesh.name));
                    if (AssetDatabase.LoadAllAssetsAtPath (materialsPath).Length == 0) {
                        FileUtil.DeleteFileOrDirectory (materialsPath);
                    }
                } else {
                    Debug.LogError ("There was an issue exporting the mesh to " + realAssetPath + filename + ". Please double check your paths, names, and files. If this occurs frequently, create an issue, or vote for the existing issue if it already exists at (https://bitbucket.org/purdyjo/draw-call-minimizer/issues) and please include all information related to this issue to make the repair as fast and seamless as possible");
                }
            }

            AssetDatabase.Refresh ();

            PrefabUtility.CreatePrefab (_exportPath + "CombinedObject.prefab", _hiddenCombinedObject, ReplacePrefabOptions.ConnectToPrefab);
        }
 void ReimportNonReadableMeshes()
 {
     IEnumerable<Mesh> allMeshes = drawCallTarget.GetComponentsInChildren<MeshFilter> ().Select(X => X.sharedMesh).Distinct();
     AssetPostprocessor postProcessor = new AssetPostprocessor ();
     float currentCount = 0.0f;
     int targetCount = allMeshes.Count ();
     foreach (Mesh m in allMeshes) {
         EditorUtility.DisplayProgressBar ("Allowing mesh to be readable", "Analyzing mesh " + ((int)currentCount + 1).ToString () + " of " + targetCount.ToString (), currentCount / targetCount);
         currentCount += 1;
         string assetPath = AssetDatabase.GetAssetPath (m);
         if (assetPath != null) {
             postProcessor.assetPath = assetPath;
             ModelImporter importer = (ModelImporter)postProcessor.assetImporter;
             if (importer != null && !importer.isReadable) {
                 importer.isReadable = true;
                 AssetDatabase.ImportAsset (assetPath);
                 AssetDatabase.Refresh ();
             }
         }
     }
     EditorUtility.ClearProgressBar ();
 }
示例#18
0
        void ReimportNonReadableMeshes(IEnumerable<Mesh> allMeshes)
        {
            allMeshes = allMeshes.Distinct ();

            AssetPostprocessor postProcessor = new AssetPostprocessor ();

            float currentCount = 0.0f;
            int targetCount = allMeshes.Count ();
            foreach (Mesh m in allMeshes) {
                EditorUtility.DisplayProgressBar ("Turning Off Readonly", "Analyzing mesh " + ((int)currentCount + 1).ToString () + " of " + targetCount.ToString (), currentCount / targetCount);
                currentCount += 1;
                string assetPath = AssetDatabase.GetAssetPath (m);

                if (assetPath != null) {
                    postProcessor.assetPath = assetPath;
                    ModelImporter importer = (ModelImporter)postProcessor.assetImporter;
                    if (importer != null && !importer.isReadable) {

                        importer.isReadable = true;
                        AssetDatabase.ImportAsset (assetPath);
                        AssetDatabase.Refresh ();
                    }
                }
            }

            EditorUtility.ClearProgressBar ();
        }
示例#19
0
        /// <summary>
        /// Exports the texture to the selected folder
        /// </summary>
        /// <returns>The texture.</returns>
        /// <param name="exportedTexture">Exported texture.</param>
        /// <param name="textureName">Texture name.</param>
        /// <param name="exportPath">Export path.</param>
        /// <param name="isNormal">If set to <c>true</c> the texture is imported as a normal map.</param>
        private Texture ExportTexture(Texture exportedTexture, string textureName, string realExportPath, bool isNormal)
        {
            using (FileStream f = new FileStream(realExportPath + textureName + ".png", FileMode.OpenOrCreate)) {
                using (BinaryWriter b = new BinaryWriter(f)) {
                    b.Write (((Texture2D)exportedTexture).EncodeToPNG ());
                }
            }

            AssetPostprocessor proc = new AssetPostprocessor ();
            AssetDatabase.Refresh ();
            string texturePath = _exportPath + textureName + ".png";
            proc.assetPath = texturePath;

            TextureImporter importer = proc.assetImporter as TextureImporter;
            importer.anisoLevel = _textureAtlasProperties.anisoLevel;
            importer.normalmap = isNormal;
            importer.filterMode = _textureAtlasProperties.filterMode;
            importer.isReadable = _textureAtlasProperties.readableTexture;
            importer.maxTextureSize = _textureAtlasProperties.maxTextureSize;
            importer.wrapMode = _textureAtlasProperties.wrapMode;
            AssetDatabase.ImportAsset (texturePath, ImportAssetOptions.ForceUpdate);
            exportedTexture = (Texture2D)AssetDatabase.LoadAssetAtPath (texturePath, typeof(Texture2D));
            AssetDatabase.Refresh ();
            return exportedTexture;
        }
 void ReimportNonReadableTextures()
 {
     IEnumerable<Texture> allTextures = drawCallTarget.GetComponentsInChildren<Renderer> ().SelectMany (X => ShaderPropertyUtility.GetAllTextures (X.sharedMaterial)).Distinct ();
     AssetPostprocessor postProcessor = new AssetPostprocessor ();
     float currentCount = 0.0f;
     int targetCount = allTextures.Count ();
     foreach (Texture t in allTextures) {
         EditorUtility.DisplayProgressBar ("Turning Off Readonly", "Analyzing texture " + ((int)currentCount + 1).ToString () + " of " + targetCount.ToString (), currentCount / targetCount);
         currentCount += 1;
         string assetPath = AssetDatabase.GetAssetPath (t);
         if (assetPath != null) {
             postProcessor.assetPath = assetPath;
             TextureImporter importer = (TextureImporter)postProcessor.assetImporter;
             if (importer != null && !importer.isReadable) {
                 importer.isReadable = true;
                 importer.textureFormat = TextureImporterFormat.ARGB32;
                 AssetDatabase.ImportAsset (assetPath);
                 AssetDatabase.Refresh ();
             }
         }
     }
     EditorUtility.ClearProgressBar ();
 }
        /// <summary>
        /// Exports the combined meshes to the folder selected in the Editor Window
        /// </summary>
        /// <param name="realAssetPath">The real asset path to be used by System.IO</param>
        private void ExportMeshes(string realAssetPath)
        {
            foreach (MeshFilter mf in _hiddenCombinedObject.GetComponentsInChildren<MeshFilter>()) {
                MeshExporter.MeshToFile(mf.sharedMesh, realAssetPath + mf.name.Replace('.', '_') + ".obj");
                AssetPostprocessor proc = new AssetPostprocessor();
                AssetDatabase.Refresh();
                proc.assetPath = AssetDatabase.GetAssetPath(_exportFolder) + "/" + mf.name.Replace('.', '_') + ".obj";

                ModelImporter importer = proc.assetImporter as ModelImporter;

                importer.generateSecondaryUV = _isGeneratingLightmapUVs;
                importer.generateAnimations = ModelImporterGenerateAnimations.None;
                importer.optimizeMesh = true;
                importer.importMaterials = false;

                AssetDatabase.ImportAsset(_exportPath + mf.name.Replace('.', '_') + ".obj", ImportAssetOptions.ForceUpdate);
                mf.sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath(_exportPath + mf.name.Replace('.', '_') + ".obj", typeof(Mesh));

                AssetDatabase.DeleteAsset(_exportPath + "/Materials/" + mf.sharedMesh.name);
                if (AssetDatabase.LoadAllAssetsAtPath(_exportPath + "/Materials/").Length == 0) {
                    FileUtil.DeleteFileOrDirectory(_exportPath + "/Materials");
                }
            }

            AssetDatabase.Refresh();

            PrefabUtility.CreatePrefab(_exportPath + "CombinedObject.prefab", _hiddenCombinedObject, ReplacePrefabOptions.ConnectToPrefab);
        }
 public bool ShouldRun(Texture2D texture, AssetPostprocessor postProcessor)
 {
     return false;
 }
    private bool SaveTexture(Texture2D tex, string textureName)
    {
        using (FileStream f = new FileStream(realExportPath + textureName, FileMode.Create)) {
            using (BinaryWriter b = new BinaryWriter(f)) {
                b.Write(((Texture2D)tex).EncodeToPNG());
            }
        }

        AssetPostprocessor proc = new AssetPostprocessor();
        AssetDatabase.Refresh();
        proc.assetPath = _exportPath + textureName;

        TextureImporter importer = proc.assetImporter as TextureImporter;
        if (importer == null) {
            Debug.LogError("TextureImporter is null");
            return false;
        }
        importer.mipmapEnabled = false;
        importer.maxTextureSize = 2048;
        importer.textureFormat = TextureImporterFormat.AutomaticTruecolor;
        AssetDatabase.ImportAsset(_exportPath + textureName, ImportAssetOptions.ForceUpdate);
        AssetDatabase.LoadAssetAtPath(_exportPath + textureName, typeof(Texture2D));
        AssetDatabase.Refresh();
        return true;
    }