private static string MeshToString(MeshFilter mf, Dictionary <string, ObjMaterial> materialList) { Mesh m = mf.sharedMesh; Material[] mats = mf.renderer.sharedMaterials; StringBuilder sb = new StringBuilder(); sb.Append("g ").Append(mf.name).Append("\n"); foreach (Vector3 lv in m.vertices) { Vector3 wv = mf.transform.TransformPoint(lv); //This is sort of ugly - inverting x-component since we're in //a different coordinate system than "everyone" is "used to". sb.Append(string.Format("v {0} {1} {2}\n", -wv.x, wv.y, wv.z)); } sb.Append("\n"); foreach (Vector3 lv in m.normals) { Vector3 wv = mf.transform.TransformDirection(lv); sb.Append(string.Format("vn {0} {1} {2}\n", -wv.x, wv.y, wv.z)); } sb.Append("\n"); foreach (Vector3 v in m.uv) { sb.Append(string.Format("vt {0} {1}\n", v.x, v.y)); } for (int material = 0; material < m.subMeshCount; material++) { sb.Append("\n"); sb.Append("usemtl ").Append(mats[material].name).Append("\n"); sb.Append("usemap ").Append(mats[material].name).Append("\n"); //See if this material is already in the materiallist. try { ObjMaterial objMaterial = new ObjMaterial(); objMaterial.name = mats[material].name; if (mats[material].mainTexture) { objMaterial.textureName = AssetDatabase.GetAssetPath(mats[material].mainTexture); } else { objMaterial.textureName = null; } materialList.Add(objMaterial.name, objMaterial); } catch (ArgumentException) { //Already in the dictionary } int[] triangles = m.GetTriangles(material); for (int i = 0; i < triangles.Length; i += 3) { //Because we inverted the x-component, we also needed to alter the triangle winding. sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n", triangles[i] + 1 + vertexOffset, triangles[i + 1] + 1 + normalOffset, triangles[i + 2] + 1 + uvOffset)); } } vertexOffset += m.vertices.Length; normalOffset += m.normals.Length; uvOffset += m.uv.Length; return(sb.ToString()); }
void DrawEditAndCompileDates(InkFile masterInkFile) { string editAndCompileDateString = ""; DateTime lastEditDate = File.GetLastWriteTime(inkFile.absoluteFilePath); editAndCompileDateString += "Last edit date " + lastEditDate.ToString(); if (masterInkFile.jsonAsset != null) { DateTime lastCompileDate = File.GetLastWriteTime(InkEditorUtils.CombinePaths(Application.dataPath, AssetDatabase.GetAssetPath(masterInkFile.jsonAsset).Substring(7))); editAndCompileDateString += "\nLast compile date " + lastCompileDate.ToString(); if (lastEditDate > lastCompileDate) { EditorGUILayout.HelpBox(editAndCompileDateString, MessageType.Warning); } else { EditorGUILayout.HelpBox(editAndCompileDateString, MessageType.None); } } else { EditorGUILayout.HelpBox(editAndCompileDateString, MessageType.None); } }
string GetPathToScene() { return((scene != null) ? AssetDatabase.GetAssetPath(scene) : String.Empty); }
void OnGUI() { scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, false); if (_labelstyle == null) { _labelstyle = new GUIStyle(EditorStyles.boldLabel); _labelstyle.fontSize = 11; } if (_labelstyle_1 == null) { _labelstyle_1 = new GUIStyle(EditorStyles.boldLabel); _labelstyle_1.fontStyle = FontStyle.BoldAndItalic; _labelstyle_1.fontSize = 11; } EditorGUILayout.Space(); GUILayout.Label("Resource Importer:", _labelstyle); EditorGUILayout.Space(); _model = EditorGUILayout.ObjectField("Select Model:", _model, typeof(GameObject), true) as GameObject; if (_model != null) { string path = AssetDatabase.GetAssetPath(_model); if (path.EndsWith(".FBX") || path.EndsWith(".fbx")) { _data.model = path; EditorGUILayout.LabelField("Path", _data.model); EditorGUILayout.Space(); _data.compression = (ModelImporterMeshCompression)EditorGUILayout.EnumPopup("Mesh Compression", _data.compression); _data.normal = (ModelImporterNormals)EditorGUILayout.EnumPopup("Normals", _data.normal); _data.tangent = (ModelImporterTangents)EditorGUILayout.EnumPopup("Tangents", _data.tangent); if (GUILayout.Button("Confirm", GUILayout.MaxWidth(80))) { XModelImporterData data = null; foreach (XModelImporterData model in _set.ModelSet) { if (model.model == _data.model) { data = model; break; } } if (data == null) { data = new XModelImporterData(); } data.model = _data.model; data.compression = _data.compression; data.normal = _data.normal; data.tangent = _data.tangent; if (!_set.ModelSet.Contains(data)) { _set.ModelSet.Add(data); } XDataIO <XModelImporterSet> .singleton.SerializeData("Assets/Editor/ResImporter/ImporterData/Model/ResourceImportXML.xml", _set); _model = null; XResImportEditor.Sets = null; AssetDatabase.Refresh(); } } else { _model = null; } } EditorGUILayout.Space(); EditorGUILayout.Space(); if (_set.ModelSet.Count > 0) { EditorGUILayout.LabelField("Resources Detail :", _labelstyle); EditorGUILayout.Space(); GUILayout.BeginHorizontal(); GUILayout.Label("", new GUILayoutOption[] { GUILayout.Width(120) }); GUILayout.Label("Path", _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(300) }); GUILayout.Label("Compression", _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(100) }); GUILayout.Label("Normal", _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(70) }); GUILayout.Label("Tangent", _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(70) }); GUILayout.Label("", new GUILayoutOption[] { GUILayout.Width(50) }); GUILayout.EndHorizontal(); foreach (XModelImporterData model in _set.ModelSet) { int n = model.model.LastIndexOf("/"); string name = model.model.Substring(n + 1); name = name.Substring(0, name.Length - 4); string path = model.model.Substring(0, n); path = path.Substring(7); GUILayout.BeginHorizontal(); GUILayout.Label(new GUIContent(name, name), _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(120) }); GUILayout.Label(new GUIContent(path, path), _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(300) }); GUILayout.Label(model.compression.ToString(), _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(100) }); GUILayout.Label(model.normal.ToString(), _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(70) }); GUILayout.Label(model.tangent.ToString(), _labelstyle_1, new GUILayoutOption[] { GUILayout.Width(70) }); if (GUILayout.Button("Edit")) { _model = AssetDatabase.LoadAssetAtPath(model.model, typeof(GameObject)) as GameObject; _data = model; } if (GUILayout.Button("ReImp")) { AssetDatabase.ImportAsset(model.model); AssetDatabase.Refresh(); } if (GUILayout.Button("Del")) { if (EditorUtility.DisplayDialog("Confirm your delete", "Are you sure to delete it?", "Ok", "Cancel")) { model.active = false; } } GUILayout.EndHorizontal(); } for (int i = _set.ModelSet.Count - 1; i >= 0; i--) { if (!_set.ModelSet[i].active) { string model = _set.ModelSet[i].model; _set.ModelSet.RemoveAt(i); XDataIO <XModelImporterSet> .singleton.SerializeData("Assets/Editor/ResImporter/ImporterData/Model/ResourceImportXML.xml", _set); XResImportEditor.Sets = null; AssetDatabase.ImportAsset(model); AssetDatabase.Refresh(); } } } EditorGUILayout.EndScrollView(); }
//static HashSet<string> _depTextureScaleList = new HashSet<string>(); // 进行过Scale的图片 public static string BuildDepTexture(Texture tex, float scale = 1f) { Debuger.Assert(tex); CDepCollectInfo result = KDepCollectInfoCaching.GetCache(tex); if (result != null) { return(result.Path); } string assetPath = AssetDatabase.GetAssetPath(tex); bool needBuild = AssetVersionControl.TryCheckNeedBuildWithMeta(assetPath); if (needBuild) { AssetVersionControl.TryMarkBuildVersion(assetPath); } Texture newTex; if (tex is Texture2D) { var tex2d = (Texture2D)tex; if (needBuild && !scale.Equals(1f)) // 需要进行缩放,才进来拷贝 { var cacheDir = "Assets/" + KEngineDef.ResourcesBuildCacheDir + "/BuildDepTexture/"; var cacheFilePath = cacheDir + Path.GetFileName(assetPath); //var needScale = !BuildedCache.ContainsKey("BuildDepTexture:" + assetPath); //if (needScale && !IsJustCollect) //{ // CFolderSyncTool.TexturePackerScaleImage(assetPath, cacheFilePath, scale); // do scale // var actionName = "BuildDepTexture:" + assetPath; // //BuildedCache[actionName] = true; // 下次就别scale了!蛋痛 // AddCache(actionName); //} newTex = AssetDatabase.LoadAssetAtPath(cacheFilePath, typeof(Texture2D)) as Texture2D; if (newTex == null) { Log.Error("TexturePacker scale failed... {0}", assetPath); newTex = tex2d; } SyncTextureImportSetting(tex2d, newTex as Texture2D); // TODO: mark to write //var texPath = AssetDatabase.GetAssetPath(tex2d); //var newTex2D = new Texture2D(tex2d.width, tex2d.height); //if (!string.IsNullOrEmpty(texPath)) // Assets内的纹理 //{ // var bytes = File.ReadAllBytes(texPath); // newTex2D.LoadImage(bytes); //} //else //{ // var bytes = tex2d.EncodeToPNG(); // newTex2D.LoadImage(bytes); //} //newTex2D.Apply(); //GC.CollectMaterial(); //// 进行缩放 //TextureScaler.Bilinear(newTex2D, (int) (tex.width*scale), (int) (tex.height*scale)); //GC.CollectMaterial(); //newTex = newTex2D; } else { newTex = tex2d; } } else { newTex = tex; if (!scale.Equals(1f)) { Log.Warning("[BuildDepTexture]非Texture2D: {0}, 无法进行Scale缩放....", tex); } } //if (!IsJustCollect) // CTextureCompressor.CompressTextureAsset(assetPath, newTex as Texture2D); string path = __GetPrefabBuildPath(assetPath); if (string.IsNullOrEmpty(path)) { Log.Warning("[BuildTexture]不是文件的Texture, 估计是Material的原始Texture?"); } result = DoBuildAssetBundle("Texture/Texture_" + path, newTex, needBuild); KDepCollectInfoCaching.SetCache(tex, result); GC.Collect(0); return(result.Path); }
public static void CreateAtlasAsset() { var selection = Selection.objects; string path = string.Empty; StringBuilder sb = new StringBuilder(); string tagName = string.Empty; foreach (Object s in selection) { if (s is DefaultAsset && (path = AssetDatabase.GetAssetPath(s)) != null && Directory.Exists(path)) { var ragName = s.name.ToLower() + "_atlas.spriteatlas"; string atlas_path = Path.Combine(path, ragName); tagName = s.name.ToLower() + "_atlas"; sb.Append("Crate atlas Asset :"); sb.Append(ragName); sb.Append("\r\n"); var allchildren = EditorUtils.getAllChildFiles(path, @"\.meta$|\.manifest$|\.DS_Store$|\.u$", null, false); int count = 0; List <int> names = new List <int>(); List <Sprite> allSprites = new List <Sprite>(); foreach (var f in allchildren) { count++; TextureImporter ti = AssetImporter.GetAtPath(f) as TextureImporter; if (ti != null) { if (ti.textureType != TextureImporterType.Sprite) { ti.textureType = TextureImporterType.Sprite; } Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(f); foreach (var item in objs) { if (item is Sprite) { sb.AppendLine(item.name); names.Add(UnityEngine.Animator.StringToHash(item.name)); allSprites.Add((Sprite)item); } } // ti.spritePackingTag = tagName; // ti.assetBundleName = tagName + Common.CHECK_ASSETBUNDLE_SUFFIX; EditorUtility.DisplayProgressBar("Processing...", "生成中... (" + count + " / " + allchildren.Count + ")", count / allchildren.Count); } else { Debug.LogWarningFormat("{0} is not Texture ", f); } } EditorUtility.ClearProgressBar(); //生成或者替换资源 var atlas = AssetDatabase.LoadAssetAtPath <SpriteAtlas>(atlas_path); if (atlas == null) { atlas = new SpriteAtlas(); AssetDatabase.CreateAsset(atlas, atlas_path); SpriteAtlasPackingSettings packSet = new SpriteAtlasPackingSettings() { blockOffset = 1, enableRotation = false, enableTightPacking = false, padding = 2, }; atlas.SetPackingSettings(packSet); SpriteAtlasTextureSettings textureSet = new SpriteAtlasTextureSettings() { readable = false, generateMipMaps = false, sRGB = false, filterMode = FilterMode.Bilinear, }; atlas.SetTextureSettings(textureSet); } SpriteAtlasExtensions.Add(atlas, allSprites.ToArray()); EditorUtility.SetDirty(atlas); var groupAssets = new List <string>(); groupAssets.Add(atlas_path); var atlasGroup = AASEditorUtility.FindGroup(tagName, AASEditorUtility.DefaltGroupSchema[0]); AASEditorUtility.SetGroupAddress(AASEditorUtility.LoadAASSetting(), atlasGroup, groupAssets); sb.AppendFormat("build {0} success count = {1} ", ragName, names.Count); AssetDatabase.SaveAssets(); } } sb.AppendLine("\r\nall completed"); Debug.Log(sb.ToString()); EditorUtils.WriteToTmpFile(tagName + ".txt", sb.ToString()); }
public static FGTextBuffer GetBuffer(UnityEngine.Object target) { string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(target)); return(GetBuffer(guid)); }
//Vector2 _instrumentScroll = Vector2.zero; public override void OnInspectorGUI() { //base.OnInspectorGUI (); MusicalDialog d = target as MusicalDialog; GUIStyle gs; EditorGUI.BeginChangeCheck(); Undo.RecordObject(d, "Change Musical Editor"); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); gs = new GUIStyle(); //gs.alignment = TextAnchor.MiddleCenter; gs.fontStyle = FontStyle.Bold; gs.fontSize = 14; EditorGUILayout.LabelField("Dialog:", gs); EditorGUI.indentLevel = 0; gs = new GUIStyle(); gs.fontSize = 9; gs.fontStyle = FontStyle.Italic; gs.alignment = TextAnchor.MiddleRight; EditorGUILayout.LabelField("Use spaces and _ (underscores) to separate into syllables.", gs); EditorGUILayout.EndHorizontal(); bool isDialogDirty = false; EditorGUILayout.BeginHorizontal(); GUI.enabled = d.dialogMode != MusicalDialog.DialogMode.Sentence; if (GUILayout.Button("SENTENCE")) { d.dialogMode = MusicalDialog.DialogMode.Sentence; isDialogDirty = true; } GUI.enabled = d.dialogMode != MusicalDialog.DialogMode.TextFile; if (GUILayout.Button("TEXT FILE")) { d.dialogMode = MusicalDialog.DialogMode.TextFile; isDialogDirty = true; } GUI.enabled = true; EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (d.dialogMode == MusicalDialog.DialogMode.Sentence) { gs = new GUIStyle(GUI.skin.textArea); gs.fontSize = 14; gs.padding = new RectOffset(10, 10, 10, 10); d.dialog = EditorGUILayout.TextArea(d.dialog, gs, GUILayout.ExpandHeight(false)); if (d.usableSyllables == 0 || _lastText != d.dialog) { isDialogDirty = true; _lastText = d.dialog; d.gameObject.name = "Dialog (" + d.dialog.Substring(0, Mathf.Min(d.dialog.Length, 6)) + "...)"; } } else if (d.dialogMode == MusicalDialog.DialogMode.TextFile) { if (!string.IsNullOrEmpty(d._editor_textFile_path) && d.textFile == null) { // restore last used text file d.textFile = AssetDatabase.LoadAssetAtPath(d._editor_textFile_path, typeof(Object)); } Object lastTextFile = d.textFile; d.textFile = EditorGUILayout.ObjectField("Text File", d.textFile, typeof(Object), false); d._editor_textFile_path = AssetDatabase.GetAssetPath(d.textFile); if (d.textFile != null && !string.IsNullOrEmpty(d._editor_textFile_path) && System.IO.Path.GetExtension(d._editor_textFile_path) != ".txt") { EditorGUILayout.HelpBox("Only .txt files work with the musical dialog", MessageType.Error); //d.textFile = null; d._editor_textFile_path = null; } if (d.textFile != null && !string.IsNullOrEmpty(d._editor_textFile_path) && !d._editor_textFile_path.Contains("Resources")) { EditorGUILayout.HelpBox("The text file must be inside the RESOURCES folder", MessageType.Error); d._editor_textFile_path = null; isDialogDirty = true; } if (d.textFile == null || d.textFile != null && (lastTextFile != d.textFile) || d._storedDialogs.Count == 0) { isDialogDirty = true; } /* * gs = GUI.skin.textArea; * gs.fontSize = 7; * gs.padding = new RectOffset(10,10,10,10); * string s = ""; * for(int i = 0; i < Mathf.Min(d._storedDialogs.Count, 2); i++) { * s += (i > 0 ? "\n\n" : "") + d._storedDialogs[i]; * } * s += "\n ... "; * EditorGUILayout.LabelField(s, gs); */ if (d.textFile == null) { EditorGUILayout.HelpBox("Load a text file", MessageType.Warning); } else if (d._editor_textFile_path != null) { EditorGUILayout.HelpBox("Text file loaded, with " + d._storedDialogs.Count + " separate dialogs :) \nPreview: '" + (d._storedDialogs.Count > 0 ? d._storedDialogs[0].Substring(0, Mathf.Min(30, d._storedDialogs[0].Length)).Trim('\n') : "") + "...'", MessageType.Info); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Reload Dialog", GUILayout.MaxWidth(120)) || isDialogDirty) { d.ParseDialog(); } gs = new GUIStyle(); gs.fontSize = 12; gs.fontStyle = FontStyle.Bold; gs.alignment = TextAnchor.MiddleRight; EditorGUILayout.LabelField((d.dialogMode == MusicalDialog.DialogMode.TextFile ? "Dialogs: " + d._storedDialogs.Count + " " : "") + "Syllables: " + d.usableSyllables + " ", gs); EditorGUILayout.EndHorizontal(); if (d.usableSyllables == 0) { EditorGUILayout.HelpBox("No syllables could be loaded", MessageType.Error); } EditorGUI.indentLevel = 0; EditorGUILayout.Space(); gs = new GUIStyle(); //gs.alignment = TextAnchor.MiddleCenter; gs.fontStyle = FontStyle.Bold; gs.fontSize = 14; EditorGUILayout.LabelField("Instruments:", gs); EditorGUI.indentLevel = 0; EditorGUILayout.BeginHorizontal(); GUI.enabled = d.instrumentMode != MusicalDialog.InstrumentMode.Single; if (GUILayout.Button("SINGLE")) { d.instrumentMode = MusicalDialog.InstrumentMode.Single; } GUI.enabled = d.instrumentMode != MusicalDialog.InstrumentMode.Ordered; if (GUILayout.Button("IN ORDER")) { d.instrumentMode = MusicalDialog.InstrumentMode.Ordered; } GUI.enabled = d.instrumentMode != MusicalDialog.InstrumentMode.Random; if (GUILayout.Button("RANDOM")) { d.instrumentMode = MusicalDialog.InstrumentMode.Random; } GUI.enabled = d.instrumentMode != MusicalDialog.InstrumentMode.Custom; if (GUILayout.Button("CUSTOM")) { d.instrumentMode = MusicalDialog.InstrumentMode.Custom; } /*if (d.dialogMode == MusicalDialog.DialogMode.Sentence) { * GUI.enabled = d.instrumentMode != MusicalDialog.InstrumentMode.Custom; * if (GUILayout.Button("CUSTOM")) d.instrumentMode = MusicalDialog.InstrumentMode.Custom; * } else { * if (d.instrumentMode == MusicalDialog.InstrumentMode.Custom) * d.instrumentMode = MusicalDialog.InstrumentMode.Single; * }*/ GUI.enabled = true; EditorGUILayout.EndHorizontal(); if (d.instrumentMode == MusicalDialog.InstrumentMode.Single) { EditorGUILayout.HelpBox("SINGLE Mode: All syllables will play the same sound.", MessageType.Info); d.baseClip = (AudioClip)EditorGUILayout.ObjectField("Default clip", d.baseClip, typeof(AudioClip), false); } if (d.instrumentMode == MusicalDialog.InstrumentMode.Ordered) { EditorGUILayout.HelpBox("RANDOM Mode: All syllables will play sounds from this list in order.", MessageType.Info); EditorUtils.DrawArray(serializedObject, "orderedClips"); } if (d.instrumentMode == MusicalDialog.InstrumentMode.Custom) { EditorGUILayout.HelpBox("CUSTOM Mode: Each syllable will play their own sound. If a syllable's clip is empty, the default clip wil be played.", MessageType.Info); if (GUILayout.Button("OPEN CUSTOM EDITOR")) { EditorWindow.GetWindow(typeof(MusicalDialogCustomWindow)); } /* * d.baseClip = (AudioClip)EditorGUILayout.ObjectField("Default clip", d.baseClip, typeof(AudioClip), false); * * //GUILayout.BeginArea(GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(EditorGUIUtility.singleLineHeight) * d.usableSyllables)); * //_instrumentScroll = EditorGUILayout.BeginScrollView(_instrumentScroll, new GUILayoutOption[]{GUILayout.MinHeight(EditorGUIUtility.singleLineHeight), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight * 10)}); * bool usingRandomClips = false; * _instrumentScroll = EditorGUILayout.BeginScrollView(_instrumentScroll, GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight * Mathf.Min(d.usableSyllables+1,10))); * int i = 0; * foreach(List<string> syllables in d._storedSyllables) { * foreach(string syllable in syllables) { * * var s = d.syllables[i]; * * GUILayout.BeginHorizontal(); * * EditorGUILayout.LabelField(syllable.Trim('\n').Trim('_').Trim(' '), GUILayout.Width(60)); * * GUI.enabled = !s.useRandomClip; * //s.clip = (AudioClip)EditorGUI.ObjectField(GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, new GUILayoutOption[]{GUILayout.Height(EditorGUIUtility.singleLineHeight), GUILayout.Width(100)}), s.clip, typeof(AudioClip)); * s.clip = (AudioClip)EditorGUILayout.ObjectField(s.clip, typeof(AudioClip), false); * GUI.enabled = true; * s.useRandomClip = EditorGUILayout.ToggleLeft("R",s.useRandomClip, GUILayout.Width(30)); * if (s.useRandomClip) usingRandomClips = true; * * s.activateTrigger = (Trigger)EditorGUILayout.ObjectField(s.activateTrigger, typeof(Trigger), true); * GUILayout.EndHorizontal(); * * i++; * } * } * EditorGUILayout.EndScrollView(); * //GUILayout.EndArea(); * EditorGUILayout.Space(); * if (usingRandomClips && d.randomClips.Length == 0) EditorGUILayout.HelpBox("Some syllables play random clips but you didn't add any!", MessageType.Error); * DrawArray(serializedObject, "randomClips"); */ } if (d.instrumentMode == MusicalDialog.InstrumentMode.Random) { EditorGUILayout.HelpBox("RANDOM Mode: All syllables will play random sounds from this list.", MessageType.Info); EditorUtils.DrawArray(serializedObject, "randomClips"); } EditorGUI.indentLevel = 0; EditorGUILayout.Space(); gs = new GUIStyle(); //gs.alignment = TextAnchor.MiddleCenter; gs.fontStyle = FontStyle.Bold; gs.fontSize = 14; EditorGUILayout.LabelField("Melody:", gs); EditorGUI.indentLevel = 0; d.useMidi = EditorGUILayout.ToggleLeft("Use MIDI melody", d.useMidi); GUI.enabled = d.useMidi; if (!string.IsNullOrEmpty(d._editor_midiFile_path) && d.midiFile == null) { // restore last used midi file d.midiFile = AssetDatabase.LoadAssetAtPath(d._editor_midiFile_path, typeof(Object)); } Object lastMidiFile = d.midiFile; d.midiFile = EditorGUILayout.ObjectField("MIDI File", d.midiFile, typeof(Object), false); d._editor_midiFile_path = AssetDatabase.GetAssetPath(d.midiFile); if (d.midiFile != null && !string.IsNullOrEmpty(d._editor_midiFile_path) && System.IO.Path.GetExtension(d._editor_midiFile_path) != ".mid") { EditorGUILayout.HelpBox("Only .mid files work with the musical dialog", MessageType.Error); //d.midiFile = null; d._editor_midiFile_path = null; } EditorGUILayout.BeginHorizontal(); if (d.midiFile != null && (d.midiEvents.Count == 0 || lastMidiFile != d.midiFile) || GUILayout.Button("Reload Notes", GUILayout.MaxWidth(120))) { d.ParseMidiFile(); } gs = new GUIStyle(); gs.fontSize = 12; gs.fontStyle = FontStyle.Bold; gs.alignment = TextAnchor.MiddleRight; int chords = 0; foreach (MusicalDialogMidiEvent e in d.midiEvents) { if (e.notes.Count > 1) { chords++; } } EditorGUILayout.LabelField("Notes: " + d.midiEvents.Count + " Chords: " + chords, gs); EditorGUILayout.EndHorizontal(); if (d.useMidi) { if (d.midiEvents.Count > 0 && d.usableSyllables > d.midiEvents.Count) { EditorGUILayout.HelpBox("There are more syllables than notes so the song will loop around", MessageType.Warning); } if (d.midiEvents.Count > 0 && d.usableSyllables < d.midiEvents.Count) { EditorGUILayout.HelpBox("There aren't as many syllables as notes so the song won't play completely", MessageType.Info); } if (d.midiEvents.Count == 0 && d.usableSyllables > 0) { EditorGUILayout.HelpBox("No notes found!", MessageType.Error); } } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Pitch change (semitones +/-)"); d.pitchSemitones = EditorGUILayout.IntField(d.pitchSemitones); EditorGUILayout.EndHorizontal(); //d.baseNote = (NotePitch)EditorGUILayout.EnumPopup("Base Note", d.baseNote); GUI.enabled = true; EditorGUILayout.Space(); gs = new GUIStyle(); //gs.alignment = TextAnchor.MiddleCenter; gs.fontStyle = FontStyle.Bold; gs.fontSize = 14; EditorGUILayout.LabelField("Settings:", gs); EditorGUI.indentLevel = 0; EditorUtils.DrawArray(serializedObject, "styles"); EditorGUILayout.Space(); d.volume = EditorGUILayout.Slider("Volume", d.volume, 0, 1); d.audioEffects_enabled = EditorGUILayout.ToggleLeft("Copy audio effects from an Audio Source", d.audioEffects_enabled); if (d.audioEffects_enabled) { EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Audio effects source:", GUILayout.MinWidth(120)); d.audioEffects_source = (AudioSource)EditorGUILayout.ObjectField(d.audioEffects_source, typeof(AudioSource), true); EditorGUILayout.EndHorizontal(); // check if there's other stuff that'd be problematic if (d.audioEffects_source != null) { d.audioEffects_source.playOnAwake = false; GameObject go = d.audioEffects_source.gameObject; string[] validTypes = new string[] { "UnityEngine.Transform", "UnityEngine.AudioSource", "UnityEngine.AudioEchoFilter", "UnityEngine.AudioChorusFilter", "UnityEngine.AudioReverbFilter", "UnityEngine.AudioLowPassFilter", "UnityEngine.AudioHighPassFilter", "UnityEngine.AudioDistortionFilter" }; foreach (Component co in go.GetComponents <Component>()) { if (!validTypes.Contains(co.GetType().ToString())) { EditorGUILayout.HelpBox("The audio effects source object has an invalid component, remove it to avoid trouble!: " + co.GetType().ToString(), MessageType.Error); } } } EditorGUI.indentLevel--; } d.autoTalk = EditorGUILayout.ToggleLeft("Talk automatically", d.autoTalk); EditorGUI.indentLevel = 1; if (d.autoTalk) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Autotalk pause (milliseconds)"); d.autoTalk_delay = EditorGUILayout.FloatField(d.autoTalk_delay); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("End-of-paragraph pause (milliseconds)"); d.autoTalk_endofparagraph_delay = EditorGUILayout.FloatField(d.autoTalk_endofparagraph_delay); EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel = 0; EditorGUILayout.Space(); gs = new GUIStyle(); //gs.alignment = TextAnchor.MiddleCenter; gs.fontStyle = FontStyle.Bold; gs.fontSize = 14; EditorGUILayout.LabelField("When the dialog ends:", gs); d.onEnd_action = (MusicalDialog.ActionOnEnd)EditorGUILayout.EnumPopup("Do", d.onEnd_action); if (d.onEnd_action == MusicalDialog.ActionOnEnd.OpenAnotherDialog) { d.onEnd_dialog = (MusicalDialog)EditorGUILayout.ObjectField("Dialog", d.onEnd_dialog, typeof(MusicalDialog), true); } if (d.onEnd_action == MusicalDialog.ActionOnEnd.TriggerSomething) { d.onEnd_trigger = (Trigger)EditorGUILayout.ObjectField("Trigger", d.onEnd_trigger, typeof(Trigger), true); } EditorGUILayout.Space(); GUI.enabled = Application.isPlaying; GUI.color = Color.green; if (GUILayout.Button("PLAY [Shift+P]" + (!Application.isPlaying ? " (Run the game to test)" : ""), GUILayout.Height(30))) { d.Play(); } GUI.color = Color.white; GUI.enabled = true; /* * f.sightRadius = EditorGUILayout.FloatField("Sight distance", f.sightRadius); * if (f.sightRadius < 0.1f) * f.sightRadius = 0.1f; * f.stopAtDistance = EditorGUILayout.FloatField("Stop at", f.stopAtDistance); * if (f.stopAtDistance < 0) * f.stopAtDistance = 0; * * f.speed = EditorGUILayout.FloatField("Speed", f.speed); * * f.animationOnSeen = EditorTools.AnimationPopup("Animation On Seen", f.GetComponentInChildren<Animation>(), f.animationOnSeen); * f.animationOnUnseen = EditorTools.AnimationPopup("Animation On Unseen", f.GetComponentInChildren<Animation>(), f.animationOnUnseen); */ if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(d); } }
public static void CreatePrefabAddCreateScript(int type) { Object[] selectsObjs = Selection.GetFiltered(typeof(object), SelectionMode.DeepAssets); for (int i = 0; i < selectsObjs.Length; i++) { bool fromLib = false; string prefabPath = AssetDatabase.GetAssetPath(selectsObjs[i]); string libPath = ""; if (prefabPath.Contains("ResourcesLib/Prefab/UI")) { libPath = Application.dataPath.Replace("Assets", "") + prefabPath; string path = prefabPath.Replace("ResourcesLib", "Resources"); Util.CreateFileDirectory(path); path = prefabPath.Replace("ResourcesLib", "Resources"); string repath = libPath.Replace("ResourcesLib", "Resources"); if (File.Exists(repath)) { AssetDatabase.DeleteAsset(path); } AssetDatabase.CopyAsset(prefabPath, path); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); prefabPath = path; fromLib = true; } if (!prefabPath.Contains("Resources/Prefab/UI")) { continue; } if (string.IsNullOrEmpty(libPath)) { libPath = Application.dataPath.Replace("Assets", "") + prefabPath.Replace("Resources", "ResourcesLib"); } if (!fromLib && File.Exists(libPath)) { Log.Error("resourceLib下已经存在此UI请在Lib下面修改生成代码"); return; } string name = selectsObjs[i].name; string packageName = prefabPath.Substring(0, prefabPath.LastIndexOf('/')); packageName = packageName.Substring(packageName.LastIndexOf('/') + 1); string scriptPath = Application.dataPath + "/Scripts/Modules/" + packageName + "/" + name + ".cs"; if (name == "FightUIRootView") { scriptPath = Application.dataPath + "/Scripts/Modules/Fight/UI/FightUIRootView.cs"; } if (name == "MainUIRootView") { scriptPath = Application.dataPath + "/Scripts/Modules/MainUI/MainUIManager.cs"; } if (name == "UI_GuideTip") { scriptPath = Application.dataPath + "/Scripts/CommonManager/Guide/UIGuide.cs"; } if (File.Exists(scriptPath)) { controlUiDeclaraStrDic.Clear(); controlUiGetStrDic.Clear(); getRamigeStrDic.Clear(); beforeLoadTextures.Clear(); List <string> reedInfos = ReadTextFile(scriptPath); string reedText = ReadTextAllFile(scriptPath); GameObject go = AssetDatabase.LoadAssetAtPath <GameObject>(prefabPath); bool hase = GetUiPrefabContorlInfo(go.transform, selectsObjs[i].name, "", 1, ""); if (hase && !fromLib) { string path = prefabPath.Replace("Resources", "ResourcesLib"); path = Application.dataPath.Replace("Assets", "") + path; Util.CreateFileDirectory(path); path = prefabPath.Replace("Resources", "ResourcesLib"); AssetDatabase.CopyAsset(prefabPath, path); } EditorUtility.SetDirty(go); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); StreamWriter sw = new StreamWriter(scriptPath, false, Encoding.UTF8); if (beforeLoadTextures.Count > 0 && !reedText.Contains("System.Collections.Generic")) { sw.WriteLine("using System.Collections.Generic;"); } for (int j = 0; j < reedInfos.Count; j++) { Log.Debug("reedInfos" + reedInfos[j]); sw.WriteLine(reedInfos[j]); if (reedInfos[j].Contains("开始UI申明")) { int k = 0; for (k = j + 1; k < reedInfos.Count; k++) { if (reedInfos[k].Contains("结束UI申明")) { break; } } foreach (var v in controlUiDeclaraStrDic) { sw.WriteLine(v.Value); } j = k - 1; } if (reedInfos[j].Contains("开始UI获取")) { bool getTexture = false; int k = 0; for (k = j + 1; k < reedInfos.Count - 1; k++) { if (reedInfos[k].Contains("结束UI获取")) { if (reedInfos[k + 1].Contains("开始texture设置")) { getTexture = true; } break; } } foreach (var v in controlUiGetStrDic) { sw.WriteLine(v.Value); } sw.WriteLine("\t\t//结束UI获取;"); j = k; if (!getTexture && getRamigeStrDic.Count > 0) { sw.WriteLine("\t\t//开始texture设置;"); foreach (var v in getRamigeStrDic) { sw.WriteLine(v.Value); } sw.WriteLine("\t\t//结束texture设置;"); } } if (reedInfos[j].Contains("开始texture设置")) { int k = 0; List <string> dic = new List <string>(); for (k = j + 1; k < reedInfos.Count; k++) { if (reedInfos[k].Contains("结束texture设置")) { break; } } foreach (var v in getRamigeStrDic) { sw.WriteLine(v.Value); } j = k - 1; } if (reedInfos[j].Contains("BeforLoadInfos")) { int k = 0; for (k = j + 1; k < reedInfos.Count; k++) { if (reedInfos[k] == ("\t}") || reedInfos[k] == (" }")) { if (reedInfos[k + 1].Contains("BeforLoadTextures")) { for (int l = k + 1; l < reedInfos.Count; l++) { if (reedInfos[l].Contains("//endTexture")) { k = l + 1; } } } else { k++; } sw.WriteLine("\t}"); sw.WriteLine("\tpublic string[] BeforLoadTextures()"); sw.WriteLine("\t{"); if (beforeLoadTextures.Count == 0) { sw.WriteLine("\t\treturn null;"); } else { string write = "\t\t string[] backs = new string[] {"; for (int m = 0; m < beforeLoadTextures.Count; m++) { string texure = beforeLoadTextures[m].ToLower(); write = string.Format("{0}\"{1}\",", write, texure); } write = write.Substring(0, write.Length - 1); write += "};"; sw.WriteLine(write); sw.WriteLine("\t\treturn backs;"); } sw.WriteLine("\t}"); sw.WriteLine("\t //endTexture"); break; } sw.WriteLine(reedInfos[k]); } j = k - 1; } } sw.Close(); } else { GameObject go = AssetDatabase.LoadAssetAtPath <GameObject>(prefabPath); if (go == null) { continue; } if (!Directory.Exists(Application.dataPath + "/Scripts/Modules/" + packageName)) { Directory.CreateDirectory(Application.dataPath + "/Scripts/Modules/" + packageName); } controlUiDeclaraStr = ""; controlUiGetStr = ""; getRamigeStr = ""; beforeLoadTextures.Clear(); bool hase = GetUiPrefabContorlInfo(go.transform, selectsObjs[i].name, ""); if (hase && !fromLib) { string path = prefabPath.Replace("Resources", "ResourcesLib"); path = Application.dataPath.Replace("Assets", "") + path; Util.CreateFileDirectory(path); path = prefabPath.Replace("Resources", "ResourcesLib"); AssetDatabase.CopyAsset(prefabPath, path); } EditorUtility.SetDirty(go); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); StreamWriter sw = new StreamWriter(scriptPath, false, Encoding.UTF8); if (beforeLoadTextures.Count > 0) { sw.WriteLine("using System.Collections.Generic;"); } sw.WriteLine("using System;"); sw.WriteLine("using UnityEngine;"); sw.WriteLine("using UnityEngine.UI;"); sw.WriteLine(); if (type == 1) { sw.WriteLine(string.Format("public class {0} : MonoBehaviour", name)); } else { sw.WriteLine(string.Format("public class {0}BeforeLoad : PanelBase", name)); sw.WriteLine("{"); sw.WriteLine(); sw.WriteLine("\tpublic string[] BeforLoadInfos()"); sw.WriteLine("\t{"); sw.WriteLine("\t\treturn null;"); sw.WriteLine("\t}"); sw.WriteLine("\tpublic string[] BeforLoadTextures()"); sw.WriteLine("\t{"); if (beforeLoadTextures.Count == 0) { sw.WriteLine("\t\treturn null;"); } else { string write = "\t\t string[] backs = new string[] {"; for (int m = 0; m < beforeLoadTextures.Count; m++) { string texure = beforeLoadTextures[m].ToLower(); write = string.Format("{0}\"{1}\",", write, texure); } write = write.Substring(0, write.Length - 1); write += "};"; sw.WriteLine(write); sw.WriteLine("\t\treturn backs;"); } sw.WriteLine("\t}"); sw.WriteLine("\t //endTexture"); sw.WriteLine("}"); sw.WriteLine(); sw.WriteLine(string.Format("public class {0} : SingletonMonoBehaviour<{0}>", name)); } sw.WriteLine("{"); sw.WriteLine(); sw.WriteLine("\tprivate Transform cachedTransform ;"); sw.WriteLine("\t//开始UI申明;"); sw.Write(controlUiDeclaraStr); sw.WriteLine("\t//结束UI申明;"); sw.WriteLine("\tprivate bool isUIinit = false;"); sw.WriteLine(); if (type == 1) { sw.WriteLine("\tvoid Awake ()"); } else { sw.WriteLine("\tprotected override void Awake ()"); } sw.WriteLine("\t{"); if (type != 1) { sw.WriteLine("\t\tbase.Awake();"); } sw.WriteLine("\t\tcachedTransform=transform;"); sw.WriteLine("\t\t//开始UI获取;"); sw.Write(controlUiGetStr); sw.WriteLine("\t\t//结束UI获取;"); if (!string.IsNullOrEmpty(getRamigeStr)) { sw.WriteLine("\t\t//开始texture设置;"); sw.Write(getRamigeStr); sw.WriteLine("\t\t//结束texture设置;"); } sw.WriteLine("\t\tisUIinit = true;"); sw.WriteLine("\t}"); sw.WriteLine("}"); sw.WriteLine(); sw.Close(); } } AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); }
protected override void OnAfterValidate() { _scenePath = AssetDatabase.GetAssetPath(sceneAsset); }
/// <summary> /// Combine all sprites into a single texture and save it to disk. /// </summary> static bool UpdateTexture(UIAtlas atlas, List <SpriteEntry> sprites) { // Get the texture for the atlas Texture2D tex = atlas.texture as Texture2D; string oldPath = (tex != null) ? AssetDatabase.GetAssetPath(tex.GetInstanceID()) : ""; string newPath = NGUIEditorTools.GetSaveableTexturePath(atlas); // Clear the read-only flag in texture file attributes if (System.IO.File.Exists(newPath)) { #if !UNITY_4_1 && !UNITY_4_0 && !UNITY_3_5 if (!AssetDatabase.IsOpenForEdit(newPath)) { Debug.LogError(newPath + " is not editable. Did you forget to do a check out?"); return(false); } #endif System.IO.FileAttributes newPathAttrs = System.IO.File.GetAttributes(newPath); newPathAttrs &= ~System.IO.FileAttributes.ReadOnly; System.IO.File.SetAttributes(newPath, newPathAttrs); } bool newTexture = (tex == null || oldPath != newPath); if (newTexture) { // Create a new texture for the atlas tex = new Texture2D(1, 1, TextureFormat.ARGB32, false); } else { // Make the atlas readable so we can save it tex = NGUIEditorTools.ImportTexture(oldPath, true, false, !atlas.premultipliedAlpha); } // Pack the sprites into this texture if (PackTextures(tex, sprites)) { byte[] bytes = tex.EncodeToPNG(); System.IO.File.WriteAllBytes(newPath, bytes); bytes = null; // Load the texture we just saved as a Texture2D AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); tex = NGUIEditorTools.ImportTexture(newPath, false, true, !atlas.premultipliedAlpha); // Update the atlas texture if (newTexture) { if (tex == null) { Debug.LogError("Failed to load the created atlas saved as " + newPath); } else { atlas.spriteMaterial.mainTexture = tex; } ReleaseSprites(sprites); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } return(true); } else { if (!newTexture) { NGUIEditorTools.ImportTexture(oldPath, false, true, !atlas.premultipliedAlpha); } //Debug.LogError("Operation canceled: The selected sprites can't fit into the atlas.\n" + // "Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead."); EditorUtility.DisplayDialog("Operation Canceled", "The selected sprites can't fit into the atlas.\n" + "Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead", "OK"); return(false); } }
bool Load(Texture2D texture) { if (texture == null) { return(true); } var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)); if (importer != null) { if (importer.userData.StartsWith("texture_combiner")) { //no error check here! //may break with different userData var userDataSplit = importer.userData.Split(' '); var rGuid = userDataSplit[1].Split(':')[1]; var gGuid = userDataSplit[2].Split(':')[1]; var bGuid = userDataSplit[3].Split(':')[1]; var aGuid = userDataSplit[4].Split(':')[1]; textureR = AssetDatabase.LoadAssetAtPath <Texture2D>(AssetDatabase.GUIDToAssetPath(rGuid)); textureG = AssetDatabase.LoadAssetAtPath <Texture2D>(AssetDatabase.GUIDToAssetPath(gGuid)); textureB = AssetDatabase.LoadAssetAtPath <Texture2D>(AssetDatabase.GUIDToAssetPath(bGuid)); textureA = AssetDatabase.LoadAssetAtPath <Texture2D>(AssetDatabase.GUIDToAssetPath(aGuid)); string errorGUID = ""; if (!string.IsNullOrEmpty(rGuid) && textureR == null) { errorGUID += "Red "; } if (!string.IsNullOrEmpty(gGuid) && textureG == null) { errorGUID += "Green "; } if (!string.IsNullOrEmpty(bGuid) && textureB == null) { errorGUID += "Blue "; } if (!string.IsNullOrEmpty(aGuid) && textureA == null) { errorGUID += "Alpha"; } sourceR = (Channel)System.Enum.Parse(typeof(Channel), userDataSplit[5].Split(':')[1]); sourceG = (Channel)System.Enum.Parse(typeof(Channel), userDataSplit[6].Split(':')[1]); sourceB = (Channel)System.Enum.Parse(typeof(Channel), userDataSplit[7].Split(':')[1]); sourceA = (Channel)System.Enum.Parse(typeof(Channel), userDataSplit[8].Split(':')[1]); textureSaved = texture; if (textureCombined != null) { textureCombined.Release(); DestroyImmediate(textureCombined); } if (textureCombinedAlpha != null) { textureCombinedAlpha.Release(); DestroyImmediate(textureCombinedAlpha); } if (!string.IsNullOrEmpty(errorGUID)) { EditorUtility.DisplayDialog("Error", "Source texture(s) couldn't be found in the project:\n\n" + errorGUID + "\n\nMaybe they have been deleted, or they GUID has been updated?", "Ok"); } return(true); } else { ShowNotification(new GUIContent("This texture doesn't seem to have been generated with the Texture Combiner")); } } return(false); }
private void Finish() { if (!references) { GetReferences(); } if (!references) { return; } string managerPath = gameName + "/Managers"; try { System.IO.Directory.CreateDirectory(Application.dataPath + "/" + managerPath); } catch (System.Exception e) { ACDebug.LogError("Wizard aborted - Could not create directory: " + Application.dataPath + "/" + managerPath + ". Please make sure the Assets direcrory is writeable, and that the intended game name contains no special characters."); Debug.LogException(e, this); pageNumber--; return; } try { ShowProgress(0f); SceneManager newSceneManager = CustomAssetUtility.CreateAsset <SceneManager> ("SceneManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/SceneManager.asset", gameName + "_SceneManager"); references.sceneManager = newSceneManager; ShowProgress(0.1f); SettingsManager newSettingsManager = CustomAssetUtility.CreateAsset <SettingsManager> ("SettingsManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/SettingsManager.asset", gameName + "_SettingsManager"); newSettingsManager.saveFileName = gameName; newSettingsManager.separateEditorSaveFiles = true; newSettingsManager.cameraPerspective = cameraPerspective; newSettingsManager.movingTurning = movingTurning; newSettingsManager.movementMethod = movementMethod; newSettingsManager.inputMethod = inputMethod; newSettingsManager.interactionMethod = interactionMethod; newSettingsManager.hotspotDetection = hotspotDetection; if (cameraPerspective == CameraPerspective.TwoPointFiveD) { newSettingsManager.forceAspectRatio = true; } references.settingsManager = newSettingsManager; ShowProgress(0.2f); ActionsManager newActionsManager = CustomAssetUtility.CreateAsset <ActionsManager> ("ActionsManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/ActionsManager.asset", gameName + "_ActionsManager"); ActionsManager defaultActionsManager = AssetDatabase.LoadAssetAtPath(Resource.MainFolderPath + "/Default/Default_ActionsManager.asset", typeof(ActionsManager)) as ActionsManager; if (defaultActionsManager != null) { newActionsManager.defaultClass = defaultActionsManager.defaultClass; newActionsManager.defaultClassName = defaultActionsManager.defaultClassName; } references.actionsManager = newActionsManager; AdventureCreator.RefreshActions(); ShowProgress(0.3f); VariablesManager newVariablesManager = CustomAssetUtility.CreateAsset <VariablesManager> ("VariablesManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/VariablesManager.asset", gameName + "_VariablesManager"); references.variablesManager = newVariablesManager; ShowProgress(0.4f); InventoryManager newInventoryManager = CustomAssetUtility.CreateAsset <InventoryManager> ("InventoryManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/InventoryManager.asset", gameName + "_InventoryManager"); references.inventoryManager = newInventoryManager; ShowProgress(0.5f); SpeechManager newSpeechManager = CustomAssetUtility.CreateAsset <SpeechManager> ("SpeechManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/SpeechManager.asset", gameName + "_SpeechManager"); newSpeechManager.ClearLanguages(); references.speechManager = newSpeechManager; ShowProgress(0.6f); CursorManager newCursorManager = CustomAssetUtility.CreateAsset <CursorManager> ("CursorManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/CursorManager.asset", gameName + "_CursorManager"); references.cursorManager = newCursorManager; ShowProgress(0.7f); MenuManager newMenuManager = CustomAssetUtility.CreateAsset <MenuManager> ("MenuManager", managerPath); AssetDatabase.RenameAsset("Assets/" + managerPath + "/MenuManager.asset", gameName + "_MenuManager"); references.menuManager = (MenuManager)newMenuManager; CursorManager defaultCursorManager = AssetDatabase.LoadAssetAtPath(Resource.MainFolderPath + "/Default/Default_CursorManager.asset", typeof(CursorManager)) as CursorManager; if (wizardMenu == WizardMenu.Blank) { if (defaultCursorManager != null) { CursorIcon useIcon = new CursorIcon(); useIcon.Copy(defaultCursorManager.cursorIcons[0], false); newCursorManager.cursorIcons.Add(useIcon); EditorUtility.SetDirty(newCursorManager); } } else { if (defaultCursorManager != null) { foreach (CursorIcon defaultIcon in defaultCursorManager.cursorIcons) { CursorIcon newIcon = new CursorIcon(); newIcon.Copy(defaultIcon, false); newCursorManager.cursorIcons.Add(newIcon); } CursorIconBase pointerIcon = new CursorIconBase(); pointerIcon.Copy(defaultCursorManager.pointerIcon); newCursorManager.pointerIcon = pointerIcon; newCursorManager.lookCursor_ID = defaultCursorManager.lookCursor_ID; } else { ACDebug.LogWarning("Cannot find Default_CursorManager asset to copy from!"); } newCursorManager.allowMainCursor = true; EditorUtility.SetDirty(newCursorManager); MenuManager defaultMenuManager = AssetDatabase.LoadAssetAtPath(Resource.MainFolderPath + "/Default/Default_MenuManager.asset", typeof(MenuManager)) as MenuManager; if (defaultMenuManager != null) { #if UNITY_EDITOR newMenuManager.drawOutlines = defaultMenuManager.drawOutlines; newMenuManager.drawInEditor = defaultMenuManager.drawInEditor; #endif newMenuManager.pauseTexture = defaultMenuManager.pauseTexture; if (wizardMenu != WizardMenu.Blank) { System.IO.Directory.CreateDirectory(Application.dataPath + "/" + gameName + "/UI"); } foreach (Menu defaultMenu in defaultMenuManager.menus) { float progress = (float)defaultMenuManager.menus.IndexOf(defaultMenu) / (float)defaultMenuManager.menus.Count; ShowProgress((progress * 0.3f) + 0.7f); Menu newMenu = ScriptableObject.CreateInstance <Menu>(); newMenu.Copy(defaultMenu, true, true); newMenu.Recalculate(); if (wizardMenu == WizardMenu.DefaultAC) { newMenu.menuSource = MenuSource.AdventureCreator; } else if (wizardMenu == WizardMenu.DefaultUnityUI) { newMenu.menuSource = MenuSource.UnityUiPrefab; } if (newMenu.pauseWhenEnabled) { bool autoSelectUI = (inputMethod == InputMethod.KeyboardOrController); newMenu.autoSelectFirstVisibleElement = autoSelectUI; } if (defaultMenu.PrefabCanvas) { string oldPath = AssetDatabase.GetAssetPath(defaultMenu.PrefabCanvas.gameObject); string newPath = "Assets/" + gameName + "/UI/" + defaultMenu.PrefabCanvas.name + ".prefab"; if (AssetDatabase.CopyAsset(oldPath, newPath)) { AssetDatabase.ImportAsset(newPath); GameObject canvasObNewPrefab = (GameObject)AssetDatabase.LoadAssetAtPath(newPath, typeof(GameObject)); newMenu.PrefabCanvas = canvasObNewPrefab.GetComponent <Canvas>(); } else { newMenu.PrefabCanvas = null; ACDebug.LogWarning("Could not copy asset " + oldPath + " to " + newPath, defaultMenu.PrefabCanvas.gameObject); } newMenu.rectTransform = null; } foreach (MenuElement newElement in newMenu.elements) { if (newElement != null) { AssetDatabase.AddObjectToAsset(newElement, newMenuManager); newElement.hideFlags = HideFlags.HideInHierarchy; } else { ACDebug.LogWarning("Null element found in " + newMenu.title + " - the interface may not be set up correctly."); } } if (newMenu != null) { AssetDatabase.AddObjectToAsset(newMenu, newMenuManager); newMenu.hideFlags = HideFlags.HideInHierarchy; newMenuManager.menus.Add(newMenu); } else { ACDebug.LogWarning("Unable to create new Menu from original '" + defaultMenu.title + "'"); } } EditorUtility.SetDirty(newMenuManager); if (newSpeechManager != null) { newSpeechManager.previewMenuName = "Subtitles"; EditorUtility.SetDirty(newSpeechManager); } } else { ACDebug.LogWarning("Cannot find Default_MenuManager asset to copy from!"); } } EditorUtility.ClearProgressBar(); ManagerPackage newManagerPackage = CreateManagerPackage(gameName, newSceneManager, newSettingsManager, newActionsManager, newVariablesManager, newInventoryManager, newSpeechManager, newCursorManager, newMenuManager); AssetDatabase.SaveAssets(); if (newManagerPackage == null || !newManagerPackage.IsFullyAssigned()) { EditorUtility.DisplayDialog("Wizard failed", "The New Game Wizard failed to generate a new 'Manager Package' file with all eight Managers assigned. Check your '/Assets/" + gameName + "/Managers' directory - the Managers may have been created, and just need assigning in the ManagerPackage asset Inspector, found in '/Assets/" + gameName + "'.", "OK"); } else if (GameObject.FindObjectOfType <KickStarter>() == null) { bool initScene = EditorUtility.DisplayDialog("Organise scene?", "Process complete. Would you like to organise the scene objects to begin working? This can be done at any time within the Scene Manager.", "Yes", "No"); if (initScene) { newSceneManager.InitialiseObjects(); } } } catch (System.Exception e) { ACDebug.LogWarning("Could not create Manager. Does the subdirectory " + managerPath + " exist?"); Debug.LogException(e, this); pageNumber--; } }
public static Object ObjectField(GUIContent label, Object obj, System.Type objType, bool allowSceneObjects, bool assetsMustBeInResourcesFolder) { obj = EditorGUILayout.ObjectField(label, obj, objType, allowSceneObjects); if (obj != null) { if (allowSceneObjects && !EditorUtility.IsPersistent(obj)) { // Object is in the scene var com = obj as Component; var go = obj as GameObject; if (com != null) { go = com.gameObject; } if (go != null && go.GetComponent <UnityReferenceHelper>() == null) { if (FixLabel("Object's GameObject must have a UnityReferenceHelper component attached")) { go.AddComponent <UnityReferenceHelper>(); } } } else if (EditorUtility.IsPersistent(obj)) { if (assetsMustBeInResourcesFolder) { string path = AssetDatabase.GetAssetPath(obj).Replace("\\", "/"); var rg = new System.Text.RegularExpressions.Regex(@"Resources/.*$"); if (!rg.IsMatch(path)) { if (FixLabel("Object must be in the 'Resources' folder")) { if (!System.IO.Directory.Exists(Application.dataPath + "/Resources")) { System.IO.Directory.CreateDirectory(Application.dataPath + "/Resources"); AssetDatabase.Refresh(); } string ext = System.IO.Path.GetExtension(path); string error = AssetDatabase.MoveAsset(path, "Assets/Resources/" + obj.name + ext); if (error == "") { path = AssetDatabase.GetAssetPath(obj); } else { Debug.LogError("Couldn't move asset - " + error); } } } if (!AssetDatabase.IsMainAsset(obj) && obj.name != AssetDatabase.LoadMainAssetAtPath(path).name) { if (FixLabel("Due to technical reasons, the main asset must\nhave the same name as the referenced asset")) { string error = AssetDatabase.RenameAsset(path, obj.name); if (error != "") { Debug.LogError("Couldn't rename asset - " + error); } } } } } } return(obj); }
public static void GenRoomPathData() { GameObject[] objArray = Selection.gameObjects; if (null == objArray) { Debug.Log("please select room res!!!"); return; } if (objArray.Length <= 0) { return; } if (null == objArray[0]) { return; } // 选择的物件 GameObject obj = GameObject.Instantiate(objArray[0]) as GameObject; Transform locator = obj.transform.Find("Locator"); if (null == locator) { Debug.Log("not exist locator!!!!"); return; } ChangeColliderLayerName(obj); GameObject colliderObj = GameObject.Find("collider"); BoxCollider box = null; if (null == colliderObj) { colliderObj = new GameObject("collider"); box = colliderObj.AddComponent <BoxCollider>(); box.size = new Vector3(mTileSize, 1f, mTileSize); } else { box = colliderObj.GetComponent <BoxCollider>(); } Vector3 offsetPos = new Vector3(locator.position.x, locator.position.y, locator.position.z); int nMaxSize = 0; for (int x = 0; x < mblockCount; x++) { for (int y = 0; y < mblockCount; y++) { Vector3 pos = new Vector3(x * mTileSize + mTileSize / 2, 0.5f, y * mTileSize + mTileSize / 2); colliderObj.transform.position = new Vector3(offsetPos.x + pos.x, offsetPos.y, offsetPos.z + pos.z); bool ishave = CheckCollider(obj, box.bounds); if (ishave) { if (nMaxSize < y) { nMaxSize = y; } if (nMaxSize < x) { nMaxSize = x; } } } } Debug.Log("nMaxSize=" + nMaxSize); GameObject preObj = GameObject.Find("preObj"); if (null == preObj) { preObj = new GameObject("preObj"); } offsetPos = new Vector3(locator.position.x, locator.position.y + 10.0f, locator.position.z); SM.SceneObstacleData obstacleData = new SM.SceneObstacleData(); obstacleData.MaxSize = nMaxSize; //nMaxSize += 2; for (int x = 0; x < nMaxSize; x++) { for (int y = 0; y < nMaxSize; y++) { Vector3 pos = new Vector3(x * mTileSize + mTileSize / 2, 0.5f, y * mTileSize + mTileSize / 2); colliderObj.transform.position = new Vector3(offsetPos.x + pos.x, offsetPos.y, offsetPos.z + pos.z); RaycastHit[] hit; hit = Physics.SphereCastAll(colliderObj.transform.position, mTileSize / 2, Vector3.down, 1000f); bool ishave = false; SM.SceneObstacleData.ObData obData = new SM.SceneObstacleData.ObData(); foreach (RaycastHit h in hit) { //Debug.Log("h.collider.gameObject.transform:" + h.collider.gameObject.transform.parent.name); if ("Collider" == h.collider.gameObject.transform.parent.name) //if (LayerMask.NameToLayer("EnableCollider") == h.collider.gameObject.layer) { if (h.collider.gameObject.transform.parent.parent.name.Contains("RemovableGate_E")) { obData.enDirection = SM.ENGateDirection.enEAST; //Debug.Log("name:" + h.collider.gameObject.transform.parent.parent.name); } else if (h.collider.gameObject.transform.parent.parent.name.Contains("RemovableGate_W")) { obData.enDirection = SM.ENGateDirection.enWEST; //Debug.Log("name:" + h.collider.gameObject.transform.parent.parent.name); } else if (h.collider.gameObject.transform.parent.parent.name.Contains("RemovableGate_N")) { obData.enDirection = SM.ENGateDirection.enNORTH; //Debug.Log("name:" + h.collider.gameObject.transform.parent.parent.name); } else if (h.collider.gameObject.transform.parent.parent.name.Contains("RemovableGate_S")) { obData.enDirection = SM.ENGateDirection.enSOUTH; //Debug.Log("name:" + h.collider.gameObject.transform.parent.parent.name); } ishave = true; break; } } obData.obstacleArray = new Vector3(x, y, ishave ? 1 : 0); obstacleData.mData.Add(obData); //////////////////////////////////////////////////// GameObject childObj = new GameObject("x_" + x.ToString("00") + "_y_" + y.ToString("00") + "(" + ishave.ToString() + ")"); childObj.transform.parent = preObj.transform; childObj.transform.position = colliderObj.transform.position; if (!ishave) { BoxCollider box1 = childObj.AddComponent <BoxCollider>(); box1.size = new Vector3(mTileSize, 0.1f, mTileSize); } } } preObj.LocalPositionY(-10f); // for (int i = 0; i < Map.GetLength(1); i++) // { // for (int j = 0; j < Map.GetLength(0); j++) // { // bool isWalkable = Mathf.CeilToInt(Map[j, i].obstacleArray.z) == 1 ? false : true; // if (!isWalkable) // continue; // for (int y = i - 1; y < i + 2; y++) // { // for (int x = j - 1; x < j + 2; x++) // { // if (y < 0 || x < 0 || y >= Map.GetLength(1) || x >= Map.GetLength(0)) // continue; // isWalkable = Mathf.CeilToInt(Map[x, y].obstacleArray.z) == 1 ? false : true; // if (!isWalkable) // continue; // Vector3 pos1 = new Vector3(j * mTileSize/* + mTileSize / 2*/, 0.5f, i * mTileSize/* + mTileSize / 2*/); // Vector3 start = new Vector3(offsetPos.x + pos1.x, offsetPos.y, offsetPos.z + pos1.z); // // Vector3 pos = new Vector3(x * mTileSize/* + mTileSize / 2*/, 0.5f, y * mTileSize/* + mTileSize / 2*/); // Vector3 end = new Vector3(offsetPos.x + pos.x, offsetPos.y, offsetPos.z + pos.z); // // UnityEngine.Debug.DrawLine(start, end, Color.green); // } // } // } // } string path = AssetDatabase.GetAssetPath(objArray[0]); Debug.Log("path=" + path); path = Path.GetDirectoryName(path); path += "/"; string fileName = path + objArray[0].name + "-bytes.bytes"; using (FileStream targetFile = new FileStream(fileName, FileMode.Create)) { byte[] buff = obstacleData.Save(); targetFile.Write(buff, 0, buff.Length); } Debug.Log("fileName=" + fileName); GameObject.DestroyImmediate(colliderObj); }
/// 使用的组建命名规则 GameObject ,go_**cr text text_**cr button ,btn_**cr image image_**cr RawImage rawI_**cr Toggle tog_**cr ToggleGroup togGroup_**cr ; /// ScrollRect scr_**cr GridLayoutGroup glayout_**cr Slider slider_**cr InputField input_**cr Canvas canvas_**cr Dropdown dropdown_**cr //type 0 表示第一次创建 1 表示之前已经创建 private static bool GetUiPrefabContorlInfo(Transform parent, string orilaName, string parentOrialName, int type = 0, string orialNameShow = "") { Debug.Log(parent.name); Debug.Log(orilaName); Debug.Log(parentOrialName); bool back = false; if (string.IsNullOrEmpty(orialNameShow)) { orialNameShow = orilaName; } if (parent.name.EndsWith("Control")) { parent.name = parent.name.Replace("Control", "cr"); EditorUtility.SetDirty(parent.gameObject); } if (parent.name.EndsWith("cr")) { string startName = parent.name.Split('_')[0]; startName = startName.ToLower(); if (type == 0) { switch (startName) { case "go": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "GameObject", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").gameObject;{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "text": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Text", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Text>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "btn": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Button", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Button>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "image": Image image = parent.GetComponent <Image>(); if (image.material.mainTexture == null) { Log.Error(orialNameShow + orialNameShow + parent + "贴图没有设置对用的mat存在错误请检查"); } controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Image", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Image>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "rawi": RawImage raimage = parent.GetComponent <RawImage>(); if (raimage != null && raimage.mainTexture != null && raimage.mainTexture.width * raimage.mainTexture.height > 50000) { string texturePath = AssetDatabase.GetAssetPath(raimage.mainTexture); string extension = Path.GetExtension(texturePath); texturePath = string.IsNullOrEmpty(extension) ? (texturePath + ".assetbundle") : texturePath.Replace(extension, ".assetbundle"); string abName = texturePath.Replace("Assets/Resources/", ""); getRamigeStr += string.Format("{0}{0}TextureManager.Instance.SetTexure({1},\"{2}\");{3}", "\t", parent.name, abName, "\r\n"); back = true; raimage.texture = null; if (!beforeLoadTextures.Contains(abName)) { beforeLoadTextures.Add(abName); } // EditorUtility.SetDirty(raimage.gameObject); } controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "RawImage", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<RawImage>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "tog": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Toggle", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Toggle>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "toggroup": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "ToggleGroup", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<ToggleGroup>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "scr": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "ScrollRect", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<ScrollRect>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "glayout": ToggleGroup group = parent.GetComponent <ToggleGroup>(); if (group != null) { controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "ToggleGroup", parent.name.Replace("glayout", "toggroup"), "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<ToggleGroup>();{3}", "\t", parent.name.Replace("glayout", "toggroup"), string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); } controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "GridLayoutGroup", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<GridLayoutGroup>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "slider": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Slider", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Slider>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "input": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "InputField", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<InputField>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "canvas": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Canvas", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Canvas>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "dropdown": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Dropdown", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Dropdown>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; case "scrollbar": controlUiDeclaraStr += string.Format("{0}private {1} {2};{3}", "\t", "Scrollbar", parent.name, "\r\n"); controlUiGetStr += string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Scrollbar>();{3}", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)), "\r\n"); break; } } else { try { switch (startName) { case "go": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "GameObject", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").gameObject;", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "text": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Text", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Text>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "btn": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Button", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Button>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "image": Image image = parent.GetComponent <Image>(); if (image.material.mainTexture == null) { Log.Error(orialNameShow + parentOrialName + parent + "贴图没有设置对用的mat存在错误请检查"); } controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Image", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Image>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "rawi": RawImage raimage = parent.GetComponent <RawImage>(); if (raimage != null && raimage.mainTexture != null && raimage.mainTexture.width * raimage.mainTexture.height > 50000) { string texturePath = AssetDatabase.GetAssetPath(raimage.mainTexture); string extension = Path.GetExtension(texturePath); texturePath = string.IsNullOrEmpty(extension) ? (texturePath + ".assetbundle") : texturePath.Replace(extension, ".assetbundle"); string abName = texturePath.Replace("Assets/Resources/", ""); getRamigeStrDic.Add(parent.name, string.Format("{0}{0}TextureManager.Instance.SetTexure({1},\"{2}\");", "\t", parent.name, abName)); back = true; raimage.texture = null; if (!beforeLoadTextures.Contains(abName)) { beforeLoadTextures.Add(abName); } //EditorUtility.SetDirty(raimage.gameObject); } controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "RawImage", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<RawImage>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "tog": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Toggle", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Toggle>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "toggroup": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "ToggleGroup", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<ToggleGroup>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "scr": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "ScrollRect", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<ScrollRect>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "glayout": ToggleGroup group = parent.GetComponent <ToggleGroup>(); if (group != null) { controlUiDeclaraStrDic.Add(parent.name.Replace("glayout", "toggroup"), string.Format("{0}private {1} {2};", "\t", "ToggleGroup", parent.name.Replace("glayout", "toggroup"))); controlUiGetStrDic.Add(parent.name.Replace("glayout", "toggroup"), string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<ToggleGroup>();", "\t", parent.name.Replace("glayout", "toggroup"), string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); } controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "GridLayoutGroup", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<GridLayoutGroup>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "slider": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Slider", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Slider>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "input": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "InputField", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<InputField>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "canvas": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Canvas", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Canvas>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "dropdown": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Dropdown", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Dropdown>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; case "scrollbar": controlUiDeclaraStrDic.Add(parent.name, string.Format("{0}private {1} {2};", "\t", "Scrollbar", parent.name)); controlUiGetStrDic.Add(parent.name, string.Format("{0}{0}{1} = cachedTransform.Find(\"{2}\").GetComponent<Scrollbar>();", "\t", parent.name, string.IsNullOrEmpty(parentOrialName) ? parent.name : (string.Format("{0}/{1}", parentOrialName, parent.name)))); break; } } catch (Exception) { Log.Error(parent.name + "可能重复了"); throw; } } } bool childBack = false; if (parent.childCount != 0) { for (int i = 0; i < parent.childCount; i++) { string _parentOrialName; if (parent.name == orilaName) { _parentOrialName = ""; } else if (string.IsNullOrEmpty(parentOrialName)) { _parentOrialName = parent.name; } else { _parentOrialName = parentOrialName + "/" + parent.name; } bool back1 = GetUiPrefabContorlInfo(parent.GetChild(i), orilaName, _parentOrialName, type, orialNameShow); childBack = back1 || childBack; } } return(back || childBack); }
public static uint BuildAssetBundle(Object asset, string path, BuildTarget buildTarget, KResourceQuality quality) { if (asset == null || string.IsNullOrEmpty(path)) { BuildError("BuildAssetBundle: {0}", path); return(0); } var assetNameWithoutDir = asset.name.Replace("/", "").Replace("\\", ""); // 防止多重目录... string tmpPrefabPath = string.Format("Assets/{0}.prefab", assetNameWithoutDir); PrefabType prefabType = PrefabUtility.GetPrefabType(asset); string relativePath = path; path = MakeSureExportPath(path, buildTarget, quality); var assetPath = AssetDatabase.GetAssetPath(asset); CheckAndLogDependencies(assetPath); uint crc = 0; if (asset is Texture2D) { if (!string.IsNullOrEmpty(assetPath)) // Assets内的纹理 // Texutre不复制拷贝一份 { _DoBuild(out crc, asset, null, path, relativePath, buildTarget); } else { // 内存的图片~临时创建Asset, 纯正的图片, 使用Sprite吧 var memoryTexture = asset as Texture2D; var memTexName = memoryTexture.name; var tmpTexPath = string.Format("Assets/Tex_{0}_{1}.png", memoryTexture.name, Path.GetRandomFileName()); Log.Warning("【BuildAssetBundle】Build一个非Asset 的Texture: {0}", memoryTexture.name); File.WriteAllBytes(tmpTexPath, memoryTexture.EncodeToPNG()); AssetDatabase.ImportAsset(tmpTexPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); var tmpTex = (Texture2D)AssetDatabase.LoadAssetAtPath(tmpTexPath, typeof(Texture2D)); asset = tmpTex; try { asset.name = memTexName; _DoBuild(out crc, asset, null, path, relativePath, buildTarget); } catch (Exception e) { Log.LogException(e); } File.Delete(tmpTexPath); if (File.Exists(tmpTexPath + ".meta")) { File.Delete(tmpTexPath + ".meta"); } } } else if ((prefabType == PrefabType.None && assetPath == string.Empty) || (prefabType == PrefabType.ModelPrefabInstance)) // 非prefab对象 { Object tmpInsObj = (GameObject)GameObject.Instantiate(asset); // 拷出来创建Prefab Object tmpPrefab = PrefabUtility.CreatePrefab(tmpPrefabPath, (GameObject)tmpInsObj, ReplacePrefabOptions.Default); CheckAndLogDependencies(tmpPrefabPath); asset = tmpPrefab; _DoBuild(out crc, asset, null, path, relativePath, buildTarget); GameObject.DestroyImmediate(tmpInsObj); AssetDatabase.DeleteAsset(tmpPrefabPath); } else if (prefabType == PrefabType.PrefabInstance) { var prefabParent = PrefabUtility.GetPrefabParent(asset); _DoBuild(out crc, prefabParent, null, path, relativePath, buildTarget); } else { //Log.Error("[Wrong asse Type] {0}", asset.GetType()); _DoBuild(out crc, asset, null, path, relativePath, buildTarget); } return(crc); }
static void Symlink(bool absolute) { string sourceFolderPath = EditorUtility.OpenFolderPanel("Select Folder Source", "", ""); // Cancelled dialog if (string.IsNullOrEmpty(sourceFolderPath)) { return; } if (sourceFolderPath.Contains(Application.dataPath)) { UnityEngine.Debug.LogWarning("Cannot create a symlink to folder in your project!"); return; } string sourceFolderName = sourceFolderPath.Split(new char[] { '/', '\\' }).LastOrDefault(); if (string.IsNullOrEmpty(sourceFolderName)) { UnityEngine.Debug.LogWarning("Couldn't deduce the folder name?"); return; } Object uobject = Selection.activeObject; string targetPath = uobject != null?AssetDatabase.GetAssetPath(uobject) : null; if (string.IsNullOrEmpty(targetPath)) { targetPath = "Assets"; } FileAttributes attribs = File.GetAttributes(targetPath); if ((attribs & FileAttributes.Directory) != FileAttributes.Directory) { targetPath = Path.GetDirectoryName(targetPath); } // Get path to project. string pathToProject = Application.dataPath.Split(new string[1] { "/Assets" }, System.StringSplitOptions.None)[0]; targetPath = string.Format("{0}/{1}/{2}", pathToProject, targetPath, sourceFolderName); if (Directory.Exists(targetPath)) { UnityEngine.Debug.LogWarning(string.Format("A folder already exists at this location, aborting link.\n{0} -> {1}", sourceFolderPath, targetPath)); return; } // Use absolute path or relative path? string sourcePath = absolute ? sourceFolderPath : GetRelativePath(sourceFolderPath, targetPath); #if UNITY_EDITOR_WIN using (Process cmd = Process.Start("CMD.exe", string.Format("/C mklink /J \"{0}\" \"{1}\"", targetPath, sourcePath))) { cmd.WaitForExit(); } #elif UNITY_EDITOR_OSX // For some reason, OSX doesn't want to create a symlink with quotes around the paths, so escape the spaces instead. sourcePath = sourcePath.Replace(" ", "\\ "); targetPath = targetPath.Replace(" ", "\\ "); string command = string.Format("ln -s {0} {1}", sourcePath, targetPath); ExecuteBashCommand(command); #elif UNITY_EDITOR_LINUX // Is Linux the same as OSX? #endif //UnityEngine.Debug.Log(string.Format("Created symlink: {0} <=> {1}", targetPath, sourceFolderPath)); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); }