Esempio n. 1
0
    private static void ExtractMaterialsFromModel()
    {
        var curSelectObjs = Selection.objects;

        if (curSelectObjs == null)
        {
            return;
        }

        foreach (var obj in curSelectObjs)
        {
            if (PrefabUtility.GetPrefabAssetType(obj) != PrefabAssetType.Model)
            {
                continue;
            }

            var assetPath  = AssetDatabase.GetAssetPath(obj);
            var loadAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath);
            foreach (var representObj in loadAssets)
            {
                if (representObj is Material)
                {
                    var savePath =
                        assetPath.Replace(".FBX", ".mat"); //Path.Combine(destinyPath + representObj.name) + ".mat";
                    savePath = AssetDatabase.GenerateUniqueAssetPath(savePath);
                    string extractResult = AssetDatabase.ExtractAsset(representObj, savePath);
                    if (string.IsNullOrEmpty(extractResult))
                    {
                        AssetDatabase.WriteImportSettingsIfDirty(assetPath);
                        AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                    }
                }
            }
        }
    }
Esempio n. 2
0
    // 从fbx模型导出材质球
    public void ExtractMaterialsFromFBX(string assetPath)
    {
        // 材质目录
        string materialFolder = Path.GetDirectoryName(assetPath) + "/Material";

        // 如果不存在该文件夹则创建一个新的
        if (!AssetDatabase.IsValidFolder(materialFolder))
        {
            AssetDatabase.CreateFolder(Path.GetDirectoryName(assetPath), "Material");
        }
        // 获取 assetPath 下所有资源。
        Object[] assets = AssetDatabase.LoadAllAssetsAtPath(assetPath);
        foreach (Object item in assets)
        {
            if (item.GetType() == typeof(Material))
            {
                string path = System.IO.Path.Combine(materialFolder, item.name) + ".mat";
                // 为资源创建一个新的唯一路径。
                path = AssetDatabase.GenerateUniqueAssetPath(path);
                // 通过在导入资源(例如,FBX 文件)中提取外部资源,在对象(例如,材质)中创建此资源。
                string value = AssetDatabase.ExtractAsset(item, path);
                // 成功提取( 如果 Unity 已成功提取资源,则返回一个空字符串)
                if (string.IsNullOrEmpty(value))
                {
                    AssetDatabase.WriteImportSettingsIfDirty(assetPath);
                    AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                }
            }
        }
        Debug.Log(Path.GetFileName(assetPath) + " 的 Material 导出成功!!");
    }
Esempio n. 3
0
    // Use this for initialization
    public void Extract()
    {
        string modelPath = EditorUtility.OpenFilePanel("Select model", "", "fbx");

        if (modelPath.StartsWith(Application.dataPath))
        {
            modelPath = "Assets" + modelPath.Substring(Application.dataPath.Length);
        }

        Object model = AssetDatabase.LoadAssetAtPath(modelPath, typeof(Object)) as Object;

        try
        {
            AssetDatabase.StartAssetEditing();

            var assetsToReload = new HashSet <string>();

            var materials = AssetDatabase.LoadAllAssetsAtPath(modelPath).Where(x => x.GetType() == typeof(Material));

            foreach (var material in materials)
            {
                Material m = material as Material;
                if (m != null)
                {
                    m.color = Color.white;
                }
                var newAssetPath = modelPath.Substring(0, modelPath.Length - model.name.Length - 4) + material.name + ".mat"; // -4 is for .fbx

                newAssetPath = AssetDatabase.GenerateUniqueAssetPath(newAssetPath);
                var error = AssetDatabase.ExtractAsset(material, newAssetPath);
                if (string.IsNullOrEmpty(error))
                {
                    assetsToReload.Add(modelPath);
                }
            }

            foreach (var path in assetsToReload)
            {
                AssetDatabase.WriteImportSettingsIfDirty(path);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
        }
        finally
        {
            AssetDatabase.StopAssetEditing();
        }
    }
Esempio n. 4
0
        private static void ExtractSubAssetContextMenu()
        {
            var asset = Selection.activeObject;
            var path  = AssetDatabase.GetAssetPath(asset);

            var savePath = EditorUtility.SaveFilePanelInProject("Save As", asset.name, string.Empty, string.Empty, path);

            if (!string.IsNullOrWhiteSpace(path))
            {
                var error = AssetDatabase.ExtractAsset(asset, savePath);

                if (!string.IsNullOrEmpty(error))
                {
                    Debug.LogError(error);
                }

                AssetDatabase.WriteImportSettingsIfDirty(path);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
        }
Esempio n. 5
0
        internal static void ExtractMaterials(string assetPath)
        {
            string modelPath          = Path.GetDirectoryName(assetPath);
            string materialsDirectory = Path.Combine(modelPath, "materials");

            _ = Directory.CreateDirectory(materialsDirectory);

            HashSet <string>     assetsToReload = new HashSet <string>();
            IEnumerable <Object> materials      = AssetDatabase.LoadAllAssetsAtPath(assetPath).Where(x => x.GetType() == typeof(Material));

            foreach (Object material in materials)
            {
                Material m = material as Material;
                if (m != null && m.mainTexture != null)
                {
                    m.color = Color.white;
                }
                string newAssetPath = Path.Combine(materialsDirectory, $"{material.name}.mat");
                newAssetPath = AssetDatabase.GenerateUniqueAssetPath(newAssetPath);
                string error = AssetDatabase.ExtractAsset(material, newAssetPath);
                if (string.IsNullOrEmpty(error))
                {
                    _ = assetsToReload.Add(assetPath);
                }
            }

            if (assetsToReload.Count > 0)
            {
                foreach (string path in assetsToReload)
                {
                    _ = AssetDatabase.WriteImportSettingsIfDirty(path);
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                }
                Debug.Log("Extracted materials");
            }
            else
            {
                Debug.LogWarning("Failed to extract materials (Already extracted?)");
            }
        }
Esempio n. 6
0
        private Material PrepareMaterial(Material oldMaterial)
        {
            if (oldMaterial == null)
            {
                return(null);
            }

            var materialFile = _materialsPath + "/" + oldMaterial.name + ".mat";
            var material     = AssetDatabase.LoadAssetAtPath <Material>(materialFile);

            if (material == null)
            {
                AssetDatabase.ExtractAsset(oldMaterial, materialFile);
                material = AssetDatabase.LoadAssetAtPath <Material>(materialFile);
            }

            material.EnableKeyword("_ALPHABLEND_ON");
            material.SetFloat("_Mode", 2.0f);
            EditorUtility.SetDirty(material);
            AssetDatabase.SaveAssets();
            return(material);
        }
Esempio n. 7
0
        private static void RenameAsset(UnityEngine.Object asset, string newName)
        {
            var pathToAsset = AssetDatabase.GetAssetPath(asset);

            AssetDatabase.RenameAsset(pathToAsset, newName);

            AssetDatabase.ExtractAsset(asset, "Assets/TestData");

            if (asset.name != newName)
            {
                var message = string.Format(
                    "Asset [{0}] not renamed when trying to RenameAsset in BulkRenamer. " +
                    "It may have been canceled because the new name was already taken by" +
                    " an object at the same path. The new name may also have contained " +
                    "special characters.\n" +
                    "OriginalPath: {1}, New Name: {1}",
                    asset.name,
                    pathToAsset,
                    newName);
                throw new System.OperationCanceledException(message);
            }
        }
Esempio n. 8
0
        // https://github.com/Unity-Technologies/UnityCsReference/blob/61f92bd79ae862c4465d35270f9d1d57befd1761/Editor/Mono/Prefabs/PrefabUtility.cs#L131
        public static void ExtractMaterialsFromAsset(AssetImporter importer, string destinationPath)
        {
            var assetsToReload = new HashSet <string>();
            var materials      = AssetDatabase.LoadAllAssetsAtPath(importer.assetPath).Where(x => x.GetType() == typeof(Material)).ToArray();

            foreach (var material in materials)
            {
                var newAssetPath = destinationPath + "/" + material.name + ".mat";
                newAssetPath = AssetDatabase.GenerateUniqueAssetPath(newAssetPath);

                var error = AssetDatabase.ExtractAsset(material, newAssetPath);
                if (string.IsNullOrEmpty(error))
                {
                    assetsToReload.Add(importer.assetPath);
                }
            }

            foreach (var path in assetsToReload)
            {
                AssetDatabase.WriteImportSettingsIfDirty(path);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
        }
 public static void ExtractAssetAtPath(this Object asset, string path)
 {
     AssetDatabase.ExtractAsset(asset, path);
 }
        private static Sprite SaveAsset(PsdLayer psdLayer, TextureImporterSettings psdUnityImport,
                                        Texture2D texture, ImportUserData importSettings, ImportLayerData layerSettings)
        {
            // Generate the file path for this layer
            string fileDir;
            string filepath = GetFilePath(psdLayer, importSettings, out fileDir);

            // Create the folder if non existent
            if (AssetDatabase.IsValidFolder(fileDir) == false)
            {
                var    subPaths     = fileDir.Split('/');
                string parentFolder = subPaths[0];
                foreach (string folder in subPaths.Skip(1))
                {
                    string targetFolder = string.Format("{0}/{1}", parentFolder, folder);
                    if (AssetDatabase.IsValidFolder(targetFolder) == false)
                    {
                        AssetDatabase.CreateFolder(parentFolder, folder);
                    }
                    parentFolder = targetFolder;
                }
            }

            // Write out the texture contents into the file
            AssetDatabase.ExtractAsset(texture, filepath);
            byte[] buf = texture.EncodeToPNG();
            File.WriteAllBytes(filepath, buf);

            AssetDatabase.ImportAsset(filepath, ImportAssetOptions.ForceUpdate);
            Texture2D textureObj = AssetDatabase.LoadAssetAtPath <Texture2D>(filepath);

            // Get the texture importer for the asset
            TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(filepath);
            // Read out the texture import settings so settings can be changed
            TextureImporterSettings texSetting = new TextureImporterSettings();

            textureImporter.ReadTextureSettings(texSetting);

            float finalPPU = psdUnityImport.spritePixelsPerUnit;

            switch (layerSettings.ScaleFactor)
            {
            case ScaleFactor.Half:
                finalPPU /= 2;
                break;

            case ScaleFactor.Quarter:
                finalPPU /= 4;
                break;
            }

            // Change settings
            texSetting.spriteAlignment     = (int)layerSettings.Alignment;
            texSetting.spritePivot         = layerSettings.Pivot;
            texSetting.spritePixelsPerUnit = finalPPU;
            texSetting.filterMode          = psdUnityImport.filterMode;
            texSetting.wrapMode            = psdUnityImport.wrapMode;
            texSetting.textureType         = TextureImporterType.Sprite;
            texSetting.spriteMode          = (int)SpriteImportMode.Single;
            texSetting.mipmapEnabled       = false;
            texSetting.alphaIsTransparency = true;
            texSetting.npotScale           = TextureImporterNPOTScale.None;
            // Set the rest of the texture settings
            textureImporter.spritePackingTag = importSettings.PackingTag;
            // Write in the texture import settings
            textureImporter.SetTextureSettings(texSetting);

            EditorUtility.SetDirty(textureObj);
            AssetDatabase.WriteImportSettingsIfDirty(filepath);
            AssetDatabase.ImportAsset(filepath, ImportAssetOptions.ForceUpdate);
            return((Sprite)AssetDatabase.LoadAssetAtPath(filepath, typeof(Sprite)));
        }