本人菜鳥一只,最近工作要求需要自己搭個服務器,然后unity資源從服務器中加載,再讓資源在客戶端動態加載出來,本人曾經接觸過把自己的電腦做成服務器,然后局域網中可以訪問你的文件夾中的資源, 沒有涉及數據庫(感覺自己好Low)。
還是進入正題吧,使用UnityEditor,在unity菜單欄中創建出一個菜單鍵,並且進入可以看見窗口。
仔細看可以看見多出來的Tools,然后就是點擊進入出現的窗口,后面也就是將這些東西導出來;
接下來,我們就來聊聊怎么樣建立出這個菜單項,舉一個unity屬性的栗子吧:
using UnityEngine;
using System.Collections;
using UnityEditor;
public class ExportTools : EditorWindow{
[MenuItem("Tools/Export")]
static void Execute()
{
Debug.Log("=====");
}
void OnGUI()
{
}
}
需要注意的是MenuItem一定得寫在方法前面,否則會報錯哦!!還有方法必須是靜態的。
接下來就是使用OnGUI寫窗口,寫button(其實本菜鳥OnGUI也不是很懂,但是還是看的懂滴)
private string savePath;
private GameObject exportObject;
private int optionalCount = 0;
private Texture2D[] optionalTexture = new Texture2D[0];
void OnGUI()
{
exportObject = EditorGUILayout.ObjectField("Export Object", exportObject, typeof(GameObject), true) as GameObject;
EditorGUILayout.Space();
optionalCount = EditorGUILayout.IntField("Optional Count", optionalCount);
for (int i = 0; i < optionalCount; i++)
{
if (optionalTexture.Length != optionalCount)
{
optionalTexture = new Texture2D[optionalCount];
}
EditorGUILayout.Space();
optionalTexture[i] = EditorGUILayout.ObjectField("Optional Textures" + i, optionalTexture[i], typeof(Texture2D), false) as Texture2D;
}
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
if (GUILayout.Button("EXPORT", GUILayout.Width(100), GUILayout.Height(20)))
{
}
EditorGUILayout.EndHorizontal();
}
這樣就實現簡單的窗口了,但是還沒有實現互動的喲
所以關鍵一步來了,實現導出按鈕的功能:
if (GUILayout.Button("EXPORT", GUILayout.Width(100), GUILayout.Height(20)))
{
if (Validate())
{
ExportAndSave(exportObject);
Clear();
}
else
{
EditorUtility.DisplayDialog("error","back check","ok");
}
}
以下代碼是在導出之前對資源的一些處理:
private void ExportAndSave(GameObject go)//保存路徑
{
savePath = EditorUtility.SaveFilePanel("Save",@"D:\",go.name,"unity3d");
Debug.Log(savePath);
Export(go,savePath);
}
private void Export(GameObject go, string filePath)
{
if (!EditorUtility.IsPersistent(go))//判斷是否在project視圖下
{
GameObject tmp = GameObject.Instantiate(go) as GameObject;
go = GetPrefab(tmp,go.name) as GameObject;
}
Object[] asset = optionalTexture;
if(File.Exists(filePath))File.Delete(filePath);
BuildPipeline.BuildAssetBundle(go,asset,filePath,BuildAssetBundleOptions.CollectDependencies,BuildTarget.StandaloneWindows);
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(go));
}
private object GetPrefab(GameObject go,string name)
{
Object result = PrefabUtility.CreateEmptyPrefab("Assets/"+name+".prefab");
result = PrefabUtility.ReplacePrefab(go,result);
Object.DestroyImmediate(go);
return result;
}
private bool Validate()//判斷資源是否為空
{
bool b1 = (exportObject == null);
bool b2 = false;
foreach (Texture2D t in optionalTexture)
{
b2 = b2 || (t == null);
}
return !(b1||b2);
}
最后
private void Clear()
{
exportObject = null;
optionalCount = 0;
}
全部重置
結束:菜鳥一名,也是從其他網站獲取的知識,也是希望擴散擴散自己覺得有用的東西吧。