close
已經好久沒來「痞客邦」來寫關於Unity 技術文章,都在Goolge Blooger 那邊撰寫比較多
回歸主題...此文章內容是Unity裡面Sprite 裡面的功能。
不多說...直接看程式碼之範例吧
忘了一件事情,此程式碼操作使用到Unity Editor 外掛編輯元件哦。
-----------------
Unity Edtor (C#):
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
public class SpriteProcessor : EditorWindow
{
private Vector2 vector2Label; // 標籤位置(BeginScrollView 用的)
private GUIStyle style = new GUIStyle(); // GUI 風格
private string spriteSegmentationType = ""; // Sprite 分割像素
private string spriteName = ""; // Sprite 分格後名稱
private int spriteTitleNumber = 0; // 分格後的名稱編號
private int spriteSegmentationNumber; // 分割數值字串轉型
// 呼叫視窗
[MenuItem(測試/Sprite寫法)]
public static void spriteWindowSetting()
{
SpriteProcessor windows = EditorWindow.GetWindow(typeof(SpriteProcessor), true, "Sprite 自動分割") as SpriteProcessor;
windows.Show();
}
// 選擇貼圖(Sprite)
static Object[] getSelectTexture()
{
return Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
}
void OnGUI()
{
style.fontSize = 18;
style.normal.textColor = Color.white;
GUI.Label(new Rect(0, 0, 100, 30), "圖片分割", style);
// Sprite 分割像素
GUILayout.BeginArea(new Rect(0, 30, 300, 100));
GUILayout.BeginHorizontal();
GUILayout.Label("Sprite 分割像素");
GUILayout.EndHorizontal();
GUILayout.EndArea();
// Sprite 分割像素輸入
GUILayout.BeginArea(new Rect(150, 30, 150, 100));
GUILayout.BeginHorizontal();
spriteSegmentationType = GUILayout.TextField(spriteSegmentationType);
GUILayout.EndHorizontal();
GUILayout.EndArea();
// Sprite標籤
GUILayout.BeginArea(new Rect(0, 110, 300, 100));
GUILayout.BeginHorizontal();
GUILayout.Label("Sprite 標簽名稱");
GUILayout.EndArea();
GUILayout.EndHorizontal();
// Sprite標籤輸入
GUILayout.BeginArea(new Rect(148, 110, 150, 100));
GUILayout.BeginHorizontal();
spriteName = GUILayout.TextField(spriteName);
GUILayout.EndHorizontal();
GUILayout.EndArea();
GUILayout.BeginArea(new Rect(200, 150, 100, 100));
GUILayout.BeginHorizontal();
if (GUILayout.Button("確定"))
SetPivots();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
// 分割動作
void SetPivots()
{
spriteTitleNumber = 0;
// 判斷轉型成功執行分割
if (int.TryParse(spriteSegmentationType, out spriteSegmentationNumber))
{
Object[] textures = getSelectTexture();
Selection.objects = new Object[0];
SpriteMetaData d = new SpriteMetaData();
foreach (Texture2D texture in textures)
{
string path = AssetDatabase.GetAssetPath(texture);
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
List newData = new List();
newData.Remove(d);
for (int x = 0; x < texture.width; x += spriteSegmentationNumber)
{
for (int y = 0; y < texture.height; y += spriteSegmentationNumber)
{
d.alignment = 9;
d.pivot = new Vector2(0.5f, 0.5f);
d.name = spriteName + "_" + (spriteTitleNumber += 1);
d.rect = new Rect(x, y, spriteSegmentationNumber, spriteSegmentationNumber);
newData.Add(d);
}
}
ti.spritesheet = newData.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
-------------- 顯示結果圖下
文章標籤
全站熱搜
留言列表