整理一些unity方便的快捷操作工具
因为在编辑扩展工具,因此脚本必须放在Editor目录下,并且引用相应的库 这里我把我使用到的库全放出来
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
变量
public static BuildAssetBundleOptions sBuildOption = //BuildAssetBundleOptions.None;
BuildAssetBundleOptions.DeterministicAssetBundle |
BuildAssetBundleOptions.ForceRebuildAssetBundle |
BuildAssetBundleOptions.StrictMode;
//private static string resExtension = "*.mp3,*.xml,*.txt,*.prefab,*.png,*.jpg,*.tga,*.unity";
static List<string> resExtension = new List<string> { ".wav", ".ogg", ".mp3", ".xml", ".prefab", ".txt", ".png", ".jpg", ".tga", ".unity", ".fbx" };
[MenuItem("Assets/NewTool/SetToSky &1")] //&1 设置快捷键ALT+1
public static void SetToSky()
{
Skybox skybox = Camera.main.GetComponent<Skybox>();
if (skybox == null)
{
skybox = Camera.main.gameObject.AddComponent<Skybox>();
}
Material mat = AssetDatabase.LoadMainAssetAtPath("assets/localres/Materials/shopInsideView_test.mat") as Material;
skybox.material = new Material(mat);
skybox.material.SetTexture("_MainTex", Selection.activeObject as Texture2D);
}
[MenuItem("Assets/NewTool/ChangeTexSize &2")]
public static void ChageSizeTex()
{
Object[] selectedAsset = Selection.GetFiltered(typeof(Texture), SelectionMode.DeepAssets);
for (int i = 0; i < selectedAsset.Length; i++)
{
Texture2D tex = selectedAsset[i] as Texture2D;
TextureImporter ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(tex));
ti.maxTextureSize = 4096;
ti.isReadable = true;
ti.wrapMode = TextureWrapMode.Clamp;
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
string imagePath = AssetDatabase.GetAssetPath(tex);
byte[] fileData = File.ReadAllBytes(imagePath);
tex.LoadImage(fileData);
Texture2D temp = ScaleTexture(tex, 4096, 2048);
byte[] pngData = temp.EncodeToJPG();
string miniImagePath = imagePath.Replace(".png", "_min.jpg");
File.WriteAllBytes(miniImagePath, pngData);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
}
}
private static Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
{
Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true);
Color[] rpixels = result.GetPixels(0);
float incX = ((float)1 / source.width) * ((float)source.width / targetWidth);
float incY = ((float)1 / source.height) * ((float)source.height / targetHeight);
for (int px = 0; px < rpixels.Length; px++)
{
rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * ((float)Mathf.Floor(px / targetWidth)));
}
result.SetPixels(rpixels, 0);
result.Apply();
return result;
}
[MenuItem("Assets/NewTool/打包AB/打包成合并的文件")]
public static void ExportAssets2OneBundle()
{
// 获取文件名,选择的文件最顶层的文件目录的名称
string save_name = Selection.GetFiltered(typeof(Object), SelectionMode.TopLevel)[0].name;
string outputPath = EditorUtility.SaveFilePanel("Save Resource", Application.streamingAssetsPath, save_name, "unity3d").Replace("\\", "/");
if (string.IsNullOrEmpty(outputPath))
{
return;
}
Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
if (selection.Length == 0)
{
return;
}
string filePath;
List<string> assetPath = new List<string>();
for (int idx = 0, count = selection.Length; idx < count; ++idx)
{
filePath = AssetDatabase.GetAssetPath(selection[idx]).Replace("\\", "/");
if (File.Exists(filePath))
{
assetPath.Add(filePath);
}
}
ExportRes2OneBundle(outputPath, assetPath.ToArray(), EditorUserBuildSettings.activeBuildTarget);
}
public static void ExportRes2OneBundle(string outputPath, string[] assetPath, BuildTarget buildTarget)
{
string msg = string.Format("打包到{0}", outputPath);
EditorUtility.DisplayProgressBar("资源打包", msg, 0.1f);
if (Directory.Exists("Export") == false)
{
Directory.CreateDirectory("Export");
}
string fileName = outputPath.GetHashCode().ToString();
AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
buildMap[0].assetBundleName = fileName;
buildMap[0].assetNames = assetPath;
EditorUtility.DisplayProgressBar("资源打包", msg, 0.5f);
BuildPipeline.BuildAssetBundles("Export", buildMap, sBuildOption, buildTarget);
EditorUtility.DisplayProgressBar("资源打包", msg, 0.9f);
string srcPath = string.Format("Export/{0}", fileName);
if (File.Exists(outputPath))
{
File.Delete(outputPath);
}
File.Move(srcPath, outputPath);
EditorUtility.ClearProgressBar();
Debug.Log(string.Format("{0}->{1}", srcPath, outputPath));
}
[MenuItem("Assets/NewTool/打包AB/打包成独立的文件")]
public static void ExportAssets2IndependentBundles()
{
string outputPath = EditorUtility.SaveFolderPanel("Save Resource", Application.dataPath, "").Replace("\\", "/");
if (string.IsNullOrEmpty(outputPath))
{
return;
}
Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
if (selection.Length == 0)
{
return;
}
Debug.Log(outputPath);
//string outputFilePath;
string filePath;
List<string> assetPath = new List<string>();
for (int idx = 0, count = selection.Length; idx < count; ++idx)
{
filePath = AssetDatabase.GetAssetPath(selection[idx]).Replace("\\", "/");
if (File.Exists(filePath))
{
assetPath.Add(filePath);
}
}
ExportRes2IndependentBundles(outputPath, assetPath.ToArray(), EditorUserBuildSettings.activeBuildTarget);
}
public static void ExportRes2IndependentBundles(string outputPath, string[] assetPath, BuildTarget buildTarget)
{
string msg = string.Format("打包到{0}", outputPath);
EditorUtility.DisplayProgressBar("资源打包", msg, 0.1f);
if (Directory.Exists("Temp") == false)
{
Directory.CreateDirectory("Temp");
}
AssetBundleBuild[] builds = new AssetBundleBuild[assetPath.Length];
string outputFilePath;
for (int idx = 0, count = assetPath.Length; idx < count; ++idx)
{
outputFilePath = string.Format("{0}/{1}", outputPath, Path.GetDirectoryName(assetPath[idx]));
outputFilePath = string.Format("{0}/{1}.unity3d", outputFilePath, Path.GetFileNameWithoutExtension(assetPath[idx]));
builds[idx].assetBundleName = outputFilePath.GetHashCode().ToString();
builds[idx].assetNames = new string[] { assetPath[idx] };
EditorUtility.DisplayProgressBar("资源打包", msg, 0.1f + idx * 1.0f / count * 0.3f);
}
BuildPipeline.BuildAssetBundles("Temp", builds, sBuildOption, EditorUserBuildSettings.activeBuildTarget);
EditorUtility.DisplayProgressBar("资源打包", msg, 0.7f);
string srcFilePath;
for (int idx = 0, count = assetPath.Length; idx < count; ++idx)
{
outputFilePath = string.Format("{0}/{1}", outputPath, Path.GetDirectoryName(assetPath[idx]));
outputFilePath = string.Format("{0}/{1}.unity3d", outputFilePath, Path.GetFileNameWithoutExtension(assetPath[idx]));
srcFilePath = string.Format("Temp/{0}", outputFilePath.GetHashCode().ToString());
if (File.Exists(srcFilePath) == false)
{
Debug.LogError(string.Format("{0} is invalid file", srcFilePath));
Debug.LogError(string.Format("{0}->{1} Failed", srcFilePath, outputFilePath));
continue;
}
if (File.Exists(outputFilePath))
{
File.Delete(outputFilePath);
}
if (Directory.Exists(Path.GetDirectoryName(outputFilePath)) == false)
{
Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath));
}
try
{
File.Move(srcFilePath, outputFilePath);
File.Delete(string.Format("{0}.manifest", srcFilePath));
}
catch (Exception ex)
{
Debug.LogError(string.Format("{0}->{1} Failed! Exception: \n{2}", srcFilePath, outputFilePath, ex));
}
EditorUtility.DisplayProgressBar("资源打包", msg, 0.7f + idx * 1.0f / count * 0.3f);
}
EditorUtility.ClearProgressBar();
}
[MenuItem("Assets/NewTool/打包AB/输出AssetBundle的内容列表")]
public static void ListAssetNames()
{
string filePath = AssetDatabase.GetAssetPath(Selection.activeObject);
if (filePath.EndsWith(".unity3d", true, null) == false)
{
return;
}
AssetBundle ab = AssetBundle.LoadFromFile(filePath);
string[] assetName = ab.GetAllAssetNames();
string output = string.Format("asset count:{0}", assetName.Length);
for (int idx = 0, count = assetName.Length; idx < count; ++idx)
{
output = string.Format("{0}\n{1}", output, assetName[idx]);
}
Debug.Log(output);
ab.Unload(false);
ab = null;
}