Unity5.6增强了2D功能,为制作2D游戏提供了很大的便利,让我们可以很方便地根据图片生成多边形碰撞体。在Sprite Editor中增加了Edit Outline的功能,让我们可以编辑图片的outline,而且unity也会在我们导入图片的时候自动地给我们调整图片的outline。
如下图所示,这么一个简单的图片有三十多个顶点,这还是在Outline Tolerance设置为0的情况下。
让我们看一下游戏场景中的情况:
上图可见,这么一个sprite需要30个顶点,28个三角面片,而其实4个顶点,两个三角面片足以胜任此工作。如果一个2D游戏的场景中有大量这种图片的话,很容易就会产生几千个顶点,无缘无故消耗游戏性能。
为了解决这个问题,需要对图片进行处理。我从图片的TextureImporter中获取outline信息,根据texture的宽高进行修改。下面是代码,有对单个Texture进行修改的,也有在导入资源的时候自动处理的:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
// Author: 邵志恒 Rick
// E-mail: [email protected]
public class AjustTexutureOutline2FourVertex : AssetPostprocessor
{
// 导入图片的时候调用
public void OnPostprocessTexture(Texture2D tx)
{
TextureImporter textureImporter = this.assetImporter as TextureImporter;
SerializedObject textureImporterSO = new SerializedObject(textureImporter);
SerializedProperty outlineSP = textureImporterSO.FindProperty("m_SpriteSheet.m_Outline");
ModifyOutline(outlineSP, tx.width, tx.height);
textureImporterSO.ApplyModifiedProperties();
}
[MenuItem("Assets/AdjustOutline")]
private static void AdjustOutline()
{
Object targetObj = Selection.activeObject;
if (targetObj && targetObj is Texture2D)
{
string path = AssetDatabase.GetAssetPath(targetObj);
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
Texture tx = AssetDatabase.LoadAssetAtPath<Texture>(path);
SerializedObject textureImporterSO = new SerializedObject(textureImporter);
SerializedProperty outlineSP = textureImporterSO.FindProperty("m_SpriteSheet.m_Outline");
ModifyOutline(outlineSP, tx.width, tx.height);
textureImporterSO.ApplyModifiedProperties();
AssetDatabase.ImportAsset(path);
}
}
[MenuItem("Assets/ProcessTexture", true)]
private static bool Texture2DValidation()
{
return Selection.activeObject.GetType() == typeof(Texture2D);
}
private static void ModifyOutline(SerializedProperty outlineSP, float width, float height)
{
if (outlineSP.arraySize == 0)
{
outlineSP.InsertArrayElementAtIndex(0);
SerializedProperty arrayElementAtIndex = outlineSP.GetArrayElementAtIndex(0);
for (int i = 0; i < 4; i++)
{
arrayElementAtIndex.InsertArrayElementAtIndex(i);
arrayElementAtIndex.GetArrayElementAtIndex(i).floatValue = 0.0f;
}
}
for (int i = 0; i < outlineSP.arraySize; i++)
{
SerializedProperty arrayElementAtIndex = outlineSP.GetArrayElementAtIndex(i);
for (int j = 0; j < arrayElementAtIndex.arraySize; j++)
{
float x, y;
if (j == 0 || j == 1)
{
x = -width / 2;
}
else
{
x = width / 2;
}
if (j == 1 || j == 2)
{
y = -height / 2;
}
else
{
y = height / 2;
}
arrayElementAtIndex.GetArrayElementAtIndex(j).vector2Value = new Vector2(x, y);
}
}
}
}