Пример #1
0
            public MeshGatherer(string pathRoot)
            {
                meshPath = pathRoot + "/" + meshFolder;
                if (EP.CreatePersistentPath(meshPath.Substring("Assets/".Length), false) > 0)
                {
                    return;
                }
                var meshGUIDs = AssetDatabase.FindAssets("t:Mesh", new[] { meshPath });

                foreach (var guid in meshGUIDs)
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    var mesh      = AssetDatabase.LoadAssetAtPath <Mesh>(assetPath);
                    reduceMeshName(mesh);
                    if (!meshAssets.ContainsKey(mesh.name))
                    {
                        meshAssets.Add(mesh.name, new Dictionary <int, Mesh>());
                    }
                    if (meshAssets[mesh.name].ContainsKey(mesh.vertexCount))
                    {
                        Debug.LogWarning($"MeshGatherer repeated asset name: {mesh.name}({mesh.vertexCount}) at {assetPath} in {meshPath}");
                        continue;
                    }
                    meshAssets[mesh.name][mesh.vertexCount] = mesh;
                }
            }
Пример #2
0
        // TODO: ExtractTextures should support list parameters for batched importing

        /// <summary>
        /// Extracts and remaps textures for use by materials
        /// </summary>
        /// <returns>True if reimport is requied</returns>
        /// <remarks>
        /// IMPORTANT: In order for extracted textures to be remapped to materials
        /// this must be called when AssetDatabase.StartAssetEditing() does not pertain
        /// so that textures can be synchronously imported for remapping.
        ///
        /// WARNING: In order to update model materials the model must be remiported:
        ///  AssetDatabase.ImportAsset(modelPath)
        ///
        /// For the implementation of the "Extract Textures" button
        /// in the "Materials" tab of the "Import Settings" Inspector panel, see:
        /// https://github.com/Unity-Technologies/UnityCsReference/
        /// Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs
        /// private void ExtractTexturesGUI()
        /// </remarks>
        public static bool ExtractTextures(string modelPath)
        {
            var modelImporter = AssetImporter.GetAtPath(modelPath) as ModelImporter;

            if (modelImporter == null)
            {
                return(false);
            }

            // Extract textures
            var texturesPath = modelPath.Substring(0, modelPath.LastIndexOf('.')) + "/Textures";
            var success      = false;        // success, not extraction count

            try {
                AssetDatabase.StartAssetEditing();
                success = modelImporter.ExtractTextures(texturesPath);
            } finally {
                AssetDatabase.StopAssetEditing();
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                // Import textures to AssetDatabase
            }

            // If no textures were imported remove folder & skip the reimport
            // NOTE: ExtractTextures will only create the texturesPath if there are textures to be extracted
            if (!success || EP.CreatePersistentPath(texturesPath.Substring("Assets/".Length), false) > 0)
            {
                return(false);
            }

            // Remap textures and reimport model
            // NOTE: Remapping will fail while StartAssetEditing() pertains (during model import)
            // since extracted textures will not be immediately imported, and so will not be found.
            var guids = AssetDatabase.FindAssets("t:Texture", new string[] { texturesPath });

            foreach (var guid in guids)
            {
                var path    = AssetDatabase.GUIDToAssetPath(guid);
                var texture = AssetDatabase.LoadAssetAtPath <Texture>(path);
                if (texture == null)
                {
                    continue;
                }
                var identifier = new AssetImporter.SourceAssetIdentifier(texture);
                modelImporter.AddRemap(identifier, texture);
            }
            return(true);
        }
Пример #3
0
            public MaterialGatherer(string pathRoot)
            {
                materialPath = pathRoot + "/" + materialFolder;
                if (EP.CreatePersistentPath(materialPath.Substring("Assets/".Length), false) > 0)
                {
                    return;
                }
                var materialGUIDs = AssetDatabase.FindAssets("t:Material", new[] { materialPath });

                foreach (var guid in materialGUIDs)
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    var material  = AssetDatabase.LoadAssetAtPath <Material>(assetPath);
                    if (materialAssets.ContainsKey(material.name))
                    {
                        Debug.LogWarning($"MaterialGatherer repeated asset name: {material.name} at {assetPath} in {materialPath}");
                        continue;
                    }
                    materialAssets.Add(material.name, material);
                }
            }
Пример #4
0
            public TextureGatherer(string pathRoot)
            {
                texturePath = pathRoot + "/" + textureFolder;
                if (EP.CreatePersistentPath(texturePath.Substring("Assets/".Length), false) > 0)
                {
                    return;
                }
                var textureGUIDs = AssetDatabase.FindAssets("t:Texture", new[] { texturePath });

                foreach (var guid in textureGUIDs)
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    var texture   = AssetDatabase.LoadAssetAtPath <Texture>(assetPath);
                    if (textureAssets.ContainsKey(texture.name))
                    {
                        Debug.LogWarning($"TextureGatherer repeated asset name: {texture.name} at {assetPath} in {texturePath}");
                        continue;
                    }
                    textureAssets.Add(texture.name, texture);
                }
            }
Пример #5
0
 public RePort()
 {
     // Ensure that import path exists
     EP.CreatePersistentPath(importPath.Substring("Assets/".Length));
 }
Пример #6
0
        /// <summary>
        /// Copies asset of type T to specified persistent path
        /// </summary>
        /// <remarks>
        /// If the specified path does not exist, it will be created using EP.CreatePersistentPath.
        /// The asset name will be a unique derivative of the name of the asset object.
        /// If assetSuffix is not specified the suffix corresponding to the asset type will be used.
        ///
        /// WARNING: When AssetDatabase.StartAssetEditing() has been called, AssetDatabase.CopyAsset
        /// and PrefabUtility.SaveAsPrefabAsset will not modify AssetDatabase, in which case the returned
        /// asset reference will be the asset argument.
        /// </remarks>
        /// <typeparam name="T">Asset type</typeparam>
        /// <param name="asset">Asset to be copied</param>
        /// <param name="assetPath">Path relative to persistent folder where asset will be created</param>
        /// <param name="assetSuffix">Optional override of default suffix for asset type</param>
        /// <returns>The asset copy, or the origin of AssetDatabase has not been updated</returns>
        public static T CopyAssetToPath <T>(T asset, string assetPath, string assetSuffix = null) where T : Object
        {
            // Ensure that the asset path folders exist
            EP.CreatePersistentPath(assetPath);
            T assetCopy = null;

            if (useEditorAction)
            {
#if UNITY_EDITOR
                // Match asset and file type, and ensure that asset will be unique
                if (assetSuffix == null)
                {
                    assetSuffix = ".asset";
                    var oldPath = AssetDatabase.GetAssetPath(asset);
                    if (oldPath != null)
                    {
                        // Preserve existing file type (important for images and models)
                        assetSuffix = oldPath.Substring(oldPath.LastIndexOf('.'));
                    }
                    else
                    {
                        // Use default file type for asset type
                        // https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
                        if (asset is GameObject)
                        {
                            assetSuffix = ".prefab";
                        }
                        if (asset is Material)
                        {
                            assetSuffix = ".mat";
                        }
                        if (asset is Cubemap)
                        {
                            assetSuffix = ".cubemap";
                        }
                        if (asset is GUISkin)
                        {
                            assetSuffix = ".GUISkin";
                        }
                        if (asset is Animation)
                        {
                            assetSuffix = ".anim";
                        }
                        // TODO: Cover other specialized types such as giparams
                    }
                }
                var newPath = "Assets/" + assetPath + "/" + asset.name + assetSuffix;
                newPath = AssetDatabase.GenerateUniqueAssetPath(newPath);
                // WARNING: (Unity2019.4 undocumented) AssetDatabase.GenerateUniqueAssetPath will trim name spaces

                // Copy asset to new path
                // NOTE: The goal is to keep the original asset in place,
                // so AssetDatabase.ExtractAsset is not used.
                if (asset is GameObject)
                {
                    var gameObject = asset as GameObject;
                    if (PrefabUtility.GetPrefabAssetType(gameObject) == PrefabAssetType.NotAPrefab)
                    {
                        assetCopy = PrefabUtility.SaveAsPrefabAsset(gameObject, newPath) as T;
                    }
                    else
                    {
                        // NOTE: PrefabUtility.SaveAsPrefabAsset cannot save an asset reference as a prefab
                        var copyObject = PrefabUtility.InstantiatePrefab(gameObject) as GameObject;
                        // NOTE: Root must be unpacked, otherwise this will yield a prefab variant
                        PrefabUtility.UnpackPrefabInstance(copyObject, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
                        assetCopy = PrefabUtility.SaveAsPrefabAsset(copyObject, newPath) as T;
                        EP.Destroy(copyObject);
                    }
                }
                else
                {
                    // IMPORTANT: SubAssets must be instantiated, otherise AssetDatabase.CreateAsset(asset, newPath) will fail
                    // with error: "Couldn't add object to asset file because the Mesh [] is already an asset at [].fbx"
                    // NOTE: AssetDatabase.ExtractAsset will register as a modification of model import settings
                    if (AssetDatabase.IsSubAsset(asset))
                    {
                        AssetDatabase.CreateAsset(Object.Instantiate(asset), newPath);
                    }
                    else
                    {
                        AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(asset), newPath);
                    }
                }
                assetCopy = AssetDatabase.LoadAssetAtPath <T>(newPath);
#endif
            }
            else
            {
                Debug.LogWarning("Runtime asset copying is not implemented");
                // TODO: For runtime version simply copy the file!
            }

            if (!assetCopy)
            {
                return(asset);                        // Continue to use asset at previous path
            }
            return(assetCopy as T);
        }