Project视图里的prefab文件都是一个蓝色的正方体,我想给它们加个预览图,暂时不知道怎么改Project视图的,但反正我想像NGUI那样有个专门的窗口存放一些常用的prefab,所以做成了如下效果:
关于如何定制窗口,可以参考雨松的教程:Unity3D研究院之拓展自定义编辑器窗口
实现思路:
主要参考自:获取unity prefab的预览图像
unity在2017.2版本可以使用官方自带API:AssetPreview.GetAssetPreview(Object m) as Texture,但此版本前此接口用于有子节点的prefab是无效的,所以只好自己动手:
实例化该prefab,创建摄像机调好参数并Render to texture保存为图片,最后删掉生成的节点毁尸灭迹。但里面只实现了3D prefab的,对于UGUI是无效的,因为UGUI节点需要放在Canvas里才行,而且计算它们包围盒的算法也不同,所以我对此做了扩展:
public static Texture GetAssetPreview(GameObject obj)
{
GameObject canvas_obj = null;
GameObject clone = GameObject.Instantiate(obj);
Transform cloneTransform = clone.transform;
bool isUINode = false;
if (cloneTransform is RectTransform)
{
//如果是UGUI节点的话就要把它们放在Canvas下了
canvas_obj = new GameObject("render canvas", typeof(Canvas));
Canvas canvas = canvas_obj.GetComponent
最后加上保存Texture为本地图片的:
public static bool SaveTextureToPNG(Texture inputTex, string save_file_name)
{
RenderTexture temp = RenderTexture.GetTemporary(inputTex.width, inputTex.height, 0, RenderTextureFormat.ARGB32);
Graphics.Blit(inputTex, temp);
bool ret = SaveRenderTextureToPNG(temp, save_file_name);
RenderTexture.ReleaseTemporary(temp);
return ret;
}
//将RenderTexture保存成一张png图片
public static bool SaveRenderTextureToPNG(RenderTexture rt, string save_file_name)
{
RenderTexture prev = RenderTexture.active;
RenderTexture.active = rt;
Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
byte[] bytes = png.EncodeToPNG();
string directory = Path.GetDirectoryName(save_file_name);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
FileStream file = File.Open(save_file_name, FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(png);
png = null;
RenderTexture.active = prev;
return true;
}
详细功能和代码请看: UGUI界面编辑器扩展集合