MarkAsChanged() 공개 메소드

Mark all widgets associated with this atlas as having changed.
public MarkAsChanged ( ) : void
리턴 void
예제 #1
0
    private static UIAtlas SetAtlasInfo(GameObject go, AtlasConfig config, Material mat)
    {
        if (go == null || config == null || !config.IsUseful() || mat == null)
        {
            return(null);
        }
        TextAsset atlasTextAsset = AssetDatabase.LoadAssetAtPath <TextAsset>(config.AtlasTxtFilePath);

        if (atlasTextAsset != null)
        {
            UIAtlas uiAtlas = go.GetComponent <UIAtlas>();
            uiAtlas.spriteMaterial = mat;
            if (uiAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(uiAtlas.texture, false, false, !uiAtlas.premultipliedAlpha);
            }

            uiAtlas.MarkAsChanged();

            NGUIJson.LoadSpriteData(uiAtlas, atlasTextAsset);
            uiAtlas.MarkAsChanged();

            return(uiAtlas);
        }
        return(null);
    }
예제 #2
0
    /// <summary>
    /// Update the sprite atlas, keeping only the sprites that are on the specified list.
    /// </summary>

    static public void UpdateAtlas(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        if (sprites.Count > 0)
        {
            // Combine all sprites into a single texture and save it
            if (UpdateTexture(atlas, sprites))
            {
                // Replace the sprites within the atlas
                ReplaceSprites(atlas, sprites);
            }

            // Release the temporary textures
            ReleaseSprites(sprites);
            EditorUtility.ClearProgressBar();
            return;
        }
        else
        {
            atlas.spriteList.Clear();
            string path = NGUIEditorTools.GetSaveableTexturePath(atlas);
            atlas.spriteMaterial.mainTexture = null;
            if (!string.IsNullOrEmpty(path))
            {
                AssetDatabase.DeleteAsset(path);
            }
        }

        atlas.MarkAsChanged();
        Selection.activeGameObject = (NGUISettings.atlas != null) ? NGUISettings.atlas.gameObject : null;
        EditorUtility.ClearProgressBar();
    }
예제 #3
0
    /// <summary>
    /// Replace the sprites within the atlas.
    /// </summary>

    static public void ReplaceSprites(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        // Get the list of sprites we'll be updating
        List <UISpriteData> spriteList = atlas.spriteList;
        List <UISpriteData> kept       = new List <UISpriteData>();

        // Run through all the textures we added and add them as sprites to the atlas
        for (int i = 0; i < sprites.Count; ++i)
        {
            SpriteEntry  se     = sprites[i];
            UISpriteData sprite = AddSprite(spriteList, se);
            kept.Add(sprite);
        }

        // Remove unused sprites
        for (int i = spriteList.Count; i > 0;)
        {
            UISpriteData sp = spriteList[--i];
            if (!kept.Contains(sp))
            {
                spriteList.RemoveAt(i);
            }
        }

        // Sort the sprites so that they are alphabetical within the atlas
        atlas.SortAlphabetically();
        atlas.MarkAsChanged();
    }
예제 #4
0
    static int MarkAsChanged(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 1);
        UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");

        obj.MarkAsChanged();
        return(0);
    }
예제 #5
0
 protected override void UpdateEffectType()
 {
     if (mEffectType != EffectType.None)
     {
         mAtlas.AddEffectMaterial(GetShaderNameByEffectType(mEffectType));
     }
     else
     {
         mAtlas.MarkAsChanged();
     }
 }
예제 #6
0
 static public int MarkAsChanged(IntPtr l)
 {
     try {
         UIAtlas self = (UIAtlas)checkSelf(l);
         self.MarkAsChanged();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
예제 #7
0
 public static UIAtlas SetAtlasInfo(GameObject go, string path, Material mat)
 {
     if (AssetDatabase.LoadAssetAtPath(path.Replace(".png", ".txt"), typeof(TextAsset)))
     {
         UIAtlas uiAtlas = go.GetComponent <UIAtlas>();
         uiAtlas.spriteMaterial = mat;
         TextAsset ta = AssetDatabase.LoadAssetAtPath(path.Replace(".png", ".txt"), typeof(TextAsset)) as TextAsset;
         NGUIJson.LoadSpriteData(uiAtlas, ta);
         uiAtlas.MarkAsChanged();
         return(uiAtlas);
     }
     return(null);
 }
예제 #8
0
    /// <summary>
    /// Update the sprite atlas, keeping only the sprites that are on the specified list.
    /// </summary>

    static public void UpdateAtlas(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        if (sprites.Count > 0)
        {
            // Combine all sprites into a single texture and save it
            if (UpdateTexture(atlas, sprites))
            {
                // Replace the sprites within the atlas
                ReplaceSprites(atlas, sprites);
            }

            // Release the temporary textures
            ReleaseSprites(sprites);
            EditorUtility.ClearProgressBar();
            //process through seperating rgb and a
            Texture rgb, alpha;
            TextureAlphaSpliter.SplitAlpha(atlas.texture, false, out rgb, out alpha);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            Debug.Log("分离为rgb+alpha 贴图");
            //update mat
            var rgba = atlas.texture;
            var mat  = atlas.spriteMaterial;
            mat.shader = Shader.Find("Unlit/Transparent Colored Alpha");
            mat.SetTexture("_AlphaTex", alpha);
            mat.SetTexture("_MainTex", rgb);
            Debug.Log("重设material");
            //save src pic
            var src = AssetDatabase.GetAssetPath(rgba);
            TextureAlphaSpliter.SaveUIRgbaTexture(src);
            Debug.Log("保存rgba");
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            return;
        }
        else
        {
            atlas.spriteList.Clear();
            string path = NGUIEditorTools.GetSaveableTexturePath(atlas);
            atlas.spriteMaterial.mainTexture = null;
            if (!string.IsNullOrEmpty(path))
            {
                AssetDatabase.DeleteAsset(path);
            }
        }

        atlas.MarkAsChanged();
        Selection.activeGameObject = (NGUISettings.atlas != null) ? NGUISettings.atlas.gameObject : null;
        EditorUtility.ClearProgressBar();
    }
예제 #9
0
    static RetType handlePrefab(string assetPath)
    {
        UIAtlas atlas = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UIAtlas)) as UIAtlas;

        if (null == atlas)
        {
            return(RetType.Ignore);
        }
        if (null == atlas.spriteMaterial || null == atlas.spriteMaterial.mainTexture)
        {
            return(RetType.Error);
        }
        string path = AssetDatabase.GetAssetPath(atlas.spriteMaterial.mainTexture);
        //缩放关联的texture/
        RetType ret = handleTexture(path);

        if (atlas.pixelSize != 1f)
        {
            return(RetType.Ignore);
        }
        atlas.pixelSize = 0.5f;
        //缩放图集坐标/
        BetterList <string> sl = atlas.GetListOfSprites();

        if (sl == null)
        {
            return(RetType.Error);
        }
        foreach (string sn in sl)
        {
            UISpriteData sd = atlas.GetSprite(sn);
            sd.x      /= 2;
            sd.y      /= 2;
            sd.width  /= 2;
            sd.height /= 2;

            sd.borderBottom /= 2;
            sd.borderLeft   /= 2;
            sd.borderRight  /= 2;
            sd.borderTop    /= 2;

            sd.paddingTop    /= 2;
            sd.paddingBottom /= 2;
            sd.paddingLeft   /= 2;
            sd.paddingRight  /= 2;
        }
        atlas.pixelSize *= 2;
        atlas.MarkAsChanged();
        return(ret);
    }
예제 #10
0
 static int MarkAsChanged(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         UIAtlas obj = (UIAtlas)ToLua.CheckObject <UIAtlas>(L, 1);
         obj.MarkAsChanged();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #11
0
        protected static void RebuildSeperateRGBandAlphaNGUIAtlas(string assetPath)
        {
            try
            {
                EditorUtility.DisplayProgressBar("设置NGUI图集", string.Format("正在进行 {0}", assetPath), 1);
                string pngFile    = Path.ChangeExtension(assetPath, "png");
                string prefabFile = Path.ChangeExtension(assetPath, "prefab");
                string matFile    = Path.ChangeExtension(assetPath, "mat");

                GameObject prefabAsset = GEditorNGUILoader.LoadAtlasPrefab(prefabFile);
                Material   matAsset    = GEditorNGUILoader.LoadETCMaterial(matFile);
                if (matAsset == null || prefabAsset == null)
                {
                    Debug.LogError(string.Format("AssetPath: {0}  Material或者预制体为空", assetPath));
                    return;
                }
                UIAtlas uiAtlas = prefabAsset.GetComponent <UIAtlas>();
                if (uiAtlas == null)
                {
                    uiAtlas = prefabAsset.AddComponent <UIAtlas>();
                }

                // 配置图集参数

                Texture2D _mainTex  = GEditorNGUILoader.LoadTexture2D(pngFile.Replace(".png", "_RGB.png"));
                Texture2D _alphaTex = GEditorNGUILoader.LoadTexture2D(pngFile.Replace(".png", "_Alpha.png"));

                TextAsset dataAsset = AssetDatabase.LoadAssetAtPath <TextAsset>(assetPath) as TextAsset;
                if (_mainTex == null || _alphaTex == null || dataAsset == null)
                {
                    Debug.LogError(string.Format("AssetPath: {0}  图集所需图片或者配置文件不存在", assetPath));
                    return;
                }
                matAsset.SetTexture("_MainTex", _mainTex);
                matAsset.SetTexture("_MainTex_A", _alphaTex);
                uiAtlas.spriteMaterial = matAsset;
                NGUIJson.LoadSpriteData(uiAtlas, dataAsset);
                uiAtlas.MarkAsChanged();
                EditorUtility.SetDirty(uiAtlas);
                AssetDatabase.SaveAssets();
            }
            catch (System.Exception ex)
            {
                Debug.LogError("Error " + ex.ToString());
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }
예제 #12
0
 private static UIAtlas SetAtlasInfo(GameObject go, string path, Material mat)
 {
     #region 第二步:给对象添加组件、给材质球关联着色器及纹理同时关联tp产生的坐标信息文件
     if (AssetDatabase.LoadAssetAtPath(path.Replace(".png", ".txt"), typeof(TextAsset)))
     {
         UIAtlas uiAtlas = go.GetComponent <UIAtlas>();
         uiAtlas.spriteMaterial = mat;
         //加载tp产生的记事本
         TextAsset ta = AssetDatabase.LoadAssetAtPath(path.Replace(".png", ".txt"), typeof(TextAsset)) as TextAsset;
         NGUIJson.LoadSpriteData(uiAtlas, ta);
         uiAtlas.MarkAsChanged();
         return(uiAtlas);
     }
     #endregion
     return(null);
 }
    public static void ApplyTexturePackerSetting(UIAtlas atlas, TextAsset ta)
    {
        if (atlas == null || ta == null)
        {
            return;
        }

        // Ensure that this atlas has valid import settings
        if (atlas.texture != null)
        {
            NGUIEditorTools.ImportTexture(atlas.texture, false, false, !atlas.premultipliedAlpha);
        }

        NGUIEditorTools.RegisterUndo("Import Sprites", atlas);
        NGUIJson.LoadSpriteData(atlas, ta);
        atlas.MarkAsChanged();
    }
예제 #14
0
    public void MarkAsChanged()
    {
        if (mReplacement != null)
        {
            mReplacement.MarkAsChanged();
        }
        UISprite[] array = NGUITools.FindActive <UISprite>();
        int        i     = 0;

        for (int num = array.Length; i < num; i++)
        {
            UISprite uISprite = array[i];
            if (CheckIfRelated(this, uISprite.atlas))
            {
                UIAtlas atlas = uISprite.atlas;
                uISprite.atlas = null;
                uISprite.atlas = atlas;
            }
        }
        UIFont[] array2 = Resources.FindObjectsOfTypeAll(typeof(UIFont)) as UIFont[];
        int      j      = 0;

        for (int num2 = array2.Length; j < num2; j++)
        {
            UIFont uIFont = array2[j];
            if (CheckIfRelated(this, uIFont.atlas))
            {
                UIAtlas atlas2 = uIFont.atlas;
                uIFont.atlas = null;
                uIFont.atlas = atlas2;
            }
        }
        UILabel[] array3 = NGUITools.FindActive <UILabel>();
        int       k      = 0;

        for (int num3 = array3.Length; k < num3; k++)
        {
            UILabel uILabel = array3[k];
            if (uILabel.bitmapFont != null && CheckIfRelated(this, uILabel.bitmapFont.atlas))
            {
                UIFont bitmapFont = uILabel.bitmapFont;
                uILabel.bitmapFont = null;
                uILabel.bitmapFont = bitmapFont;
            }
        }
    }
예제 #15
0
    public static int MarkAsChanged(IntPtr l)
    {
        int result;

        try
        {
            UIAtlas uIAtlas = (UIAtlas)LuaObject.checkSelf(l);
            uIAtlas.MarkAsChanged();
            LuaObject.pushValue(l, true);
            result = 1;
        }
        catch (Exception e)
        {
            result = LuaObject.error(l, e);
        }
        return(result);
    }
예제 #16
0
    static private void UpdateUIAtlas(UIAtlas atlas, List <UIAtlasMaker.SpriteEntry> sprites, out Texture2D atlasTex)
    {
        atlasTex = null;
        if (
            (null == atlas) ||
            (null == sprites) ||
            (0 == sprites.Count)
            )
        {
            return;
        }

        if (UpdateTexture(atlas, sprites, out atlasTex))
        {
            UIAtlasMaker.ReplaceSprites(atlas, sprites);
        }

        UIAtlasMaker.ReleaseSprites(sprites);

        atlas.MarkAsChanged();
    }
예제 #17
0
    private void ReplaceSprites(UIAtlas atlas, List <DynamicAtlas.SpriteEntry> sprites)
    {
        List <UISpriteData> spriteList = atlas.spriteList;
        List <UISpriteData> list       = new List <UISpriteData>();

        for (int i = 0; i < sprites.Count; i++)
        {
            DynamicAtlas.SpriteEntry se   = sprites[i];
            UISpriteData             item = this.AddSprite(spriteList, se);
            list.Add(item);
        }
        int count = spriteList.Count;

        while (count > 0)
        {
            UISpriteData spriteData = spriteList[--count];
            if (list.Contains(spriteData))
            {
                spriteList.RemoveAt(count);
            }
        }
        atlas.MarkAsChanged();
    }
예제 #18
0
    /// <summary>
    /// Update the sprite atlas, keeping only the sprites that are on the specified list.
    /// </summary>

    static public void UpdateAtlas(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        if (sprites.Count > 0)
        {
            // Combine all sprites into a single texture and save it
            if (UpdateTexture(atlas, sprites))
            {
                // Replace the sprites within the atlas
                ReplaceSprites(atlas, sprites);
            }

            // Release the temporary textures
            ReleaseSprites(sprites);
            return;
        }
        else
        {
            atlas.spriteList.Clear();
            NGUITools.Destroy(atlas.spriteMaterial.mainTexture);
            atlas.spriteMaterial.mainTexture = null;
        }

        atlas.MarkAsChanged();
    }
예제 #19
0
	/// <summary>
	/// Draw the inspector widget.
	/// </summary>

	public override void OnInspectorGUI ()
	{
		NGUIEditorTools.SetLabelWidth(80f);
		mAtlas = target as UIAtlas;

		UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

		GUILayout.Space(6f);

		if (mAtlas.replacement != null)
		{
			mType = AtlasType.Reference;
			mReplacement = mAtlas.replacement;
		}

		GUILayout.BeginHorizontal();
		AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);
		GUILayout.Space(18f);
		GUILayout.EndHorizontal();

		if (mType != after)
		{
			if (after == AtlasType.Normal)
			{
				mType = AtlasType.Normal;
				OnSelectAtlas(null);
			}
			else
			{
				mType = AtlasType.Reference;
			}
		}

		if (mType == AtlasType.Reference)
		{
			ComponentSelector.Draw<UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

			GUILayout.Space(6f);
			EditorGUILayout.HelpBox("You can have one atlas simply point to " +
				"another one. This is useful if you want to be " +
				"able to quickly replace the contents of one " +
				"atlas with another one, for example for " +
				"swapping an SD atlas with an HD one, or " +
				"replacing an English atlas with a Chinese " +
				"one. All the sprites referencing this atlas " +
				"will update their references to the new one.", MessageType.Info);

			if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
			{
				NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
				mAtlas.replacement = mReplacement;
				NGUITools.SetDirty(mAtlas);
			}
			return;
		}

		//GUILayout.Space(6f);
		Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

		if (mAtlas.spriteMaterial != mat)
		{
			NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
			mAtlas.spriteMaterial = mat;

			// Ensure that this atlas has valid import settings
			if (mAtlas.texture != null) NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);

			mAtlas.MarkAsChanged();
		}

		if (mat != null)
		{
			TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

			if (ta != null)
			{
				// Ensure that this atlas has valid import settings
				if (mAtlas.texture != null) NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);

				NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
				NGUIJson.LoadSpriteData(mAtlas, ta);
				if (sprite != null) sprite = mAtlas.GetSprite(sprite.name);
				mAtlas.MarkAsChanged();
			}

			float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

			if (pixelSize != mAtlas.pixelSize)
			{
				NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
				mAtlas.pixelSize = pixelSize;
			}
		}

		if (mAtlas.spriteMaterial != null)
		{
			Color blueColor = new Color(0f, 0.7f, 1f, 1f);
			Color greenColor = new Color(0.4f, 1f, 0f, 1f);

			if (sprite == null && mAtlas.spriteList.Count > 0)
			{
				string spriteName = NGUISettings.selectedSprite;
				if (!string.IsNullOrEmpty(spriteName)) sprite = mAtlas.GetSprite(spriteName);
				if (sprite == null) sprite = mAtlas.spriteList[0];
			}

			if (sprite != null)
			{
				if (sprite == null) return;
					
				Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

				if (tex != null)
				{
					if (!NGUIEditorTools.DrawHeader("Sprite Details")) return;

					NGUIEditorTools.BeginContents();

					GUILayout.Space(3f);
					NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
					GUILayout.Space(6f);

					GUI.changed = false;

					GUI.backgroundColor = greenColor;
					NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
					NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

					EditorGUILayout.Separator();
					GUI.backgroundColor = blueColor;
					NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
					NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

					EditorGUILayout.Separator();
					GUI.backgroundColor = Color.white;
					NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
					NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

					if (GUI.changed)
					{
						NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
						
						sprite.x = sizeA.x;
						sprite.y = sizeA.y;
						sprite.width = sizeB.x;
						sprite.height = sizeB.y;

						sprite.paddingLeft = padA.x;
						sprite.paddingRight = padA.y;
						sprite.paddingBottom = padB.x;
						sprite.paddingTop = padB.y;

						sprite.borderLeft = borderA.x;
						sprite.borderRight = borderA.y;
						sprite.borderBottom = borderB.x;
						sprite.borderTop = borderB.y;

						MarkSpriteAsDirty();
					}

					GUILayout.Space(3f);

					GUILayout.BeginHorizontal();

					if (GUILayout.Button("Duplicate"))
					{
						UIAtlasMaker.SpriteEntry se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
						if (se != null) NGUISettings.selectedSprite = se.name;
					}

					if (GUILayout.Button("Save As..."))
					{
						string path = EditorUtility.SaveFilePanelInProject("Save As", sprite.name + ".png", "png", "Extract sprite into which file?");

						if (!string.IsNullOrEmpty(path))
						{
							UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

							if (se != null)
							{
								byte[] bytes = se.tex.EncodeToPNG();
								File.WriteAllBytes(path, bytes);
								AssetDatabase.ImportAsset(path);
								if (se.temporaryTexture) DestroyImmediate(se.tex);
							}
						}
					}
					GUILayout.EndHorizontal();
					NGUIEditorTools.EndContents();
				}

				if (NGUIEditorTools.DrawHeader("Modify"))
				{
					NGUIEditorTools.BeginContents();

					EditorGUILayout.BeginHorizontal();
					GUILayout.Space(20f);
					EditorGUILayout.BeginVertical();

					NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

					if (GUILayout.Button("Add a Shadow")) AddShadow(sprite);
					if (GUILayout.Button("Add a Soft Outline")) AddOutline(sprite);

					if (GUILayout.Button("Add a Transparent Border")) AddTransparentBorder(sprite);
					if (GUILayout.Button("Add a Clamped Border")) AddClampedBorder(sprite);
					if (GUILayout.Button("Add a Tiled Border")) AddTiledBorder(sprite);
					EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
					if (GUILayout.Button("Crop Border")) CropBorder(sprite);
					EditorGUI.EndDisabledGroup();

					EditorGUILayout.EndVertical();
					GUILayout.Space(20f);
					EditorGUILayout.EndHorizontal();

					NGUIEditorTools.EndContents();
				}

				if (NGUIEditorTools.previousSelection != null)
				{
					GUILayout.Space(3f);
					GUI.backgroundColor = Color.green;

					if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
					{
						NGUIEditorTools.SelectPrevious();
					}
					GUI.backgroundColor = Color.white;
				}
			}
		}
	}
예제 #20
0
    public static UIAtlas CreateAtlas(string atlasName, Device device, AtlasType atlasType)
    {
        List <UISpriteData> oldSpriteData;

#if RSATLASHELPER_DEBUG
        Debug.Log(string.Format("AddNewAtlas; atlasName = {0}, device = {1}, atlasType = {2}", atlasName, device, atlasType));
#endif

        string texturesDir = GetAtlasTexturesDirectory(atlasName, device, atlasType);

        DirectoryInfo dirInfo = new DirectoryInfo("Assets/" + texturesDir);
        if (dirInfo == null || !dirInfo.Exists)
        {
            Debug.LogWarning("Directory does not exist; " + atlasName + ", for device: " + device + " " + texturesDir);
            return(null);
        }
        List <FileInfo> fis;
        GetTextureAssets(dirInfo, out fis);

        if (fis == null && fis.Count == 0)
        {
            Debug.LogWarning("Directory empty; " + atlasName + ", for device: " + device);
            return(null);
        }

        UIAtlas newAtlas = CreateAtlasInternal(atlasName, device, atlasType, out oldSpriteData);
        if (newAtlas == null)
        {
            Debug.LogWarning("Could not create atlas for " + atlasName + ", device = " + device);
            return(null);
        }

        NGUISettings.atlas            = newAtlas;
        NGUISettings.atlasPadding     = 2;
        NGUISettings.atlasTrimming    = false;
        NGUISettings.forceSquareAtlas = true;
        NGUISettings.allow4096        = (atlasType == AtlasType.HD);
        NGUISettings.fontTexture      = null;
        NGUISettings.unityPacking     = false;

        if (device == Device.Tablet || device == Device.Standalone)
        {
            newAtlas.pixelSize = (atlasType == AtlasType.HD) ? 1f : 2f;
        }
        else
        {
            newAtlas.pixelSize = 1f;
        }

        EditorUtility.SetDirty(newAtlas.gameObject);

        List <Texture> textures = new List <Texture>();

        foreach (FileInfo fi in fis)
        {
            string textureName = "Assets" + texturesDir + fi.Name;

            Texture2D tex = AssetDatabase.LoadAssetAtPath(textureName, typeof(Texture2D)) as Texture2D;

            TextureImporter texImporter = AssetImporter.GetAtPath(textureName) as TextureImporter;
            texImporter.textureType         = TextureImporterType.Default;
            texImporter.npotScale           = TextureImporterNPOTScale.None;
            texImporter.generateCubemap     = TextureImporterGenerateCubemap.None;
            texImporter.normalmap           = false;
            texImporter.linearTexture       = true;
            texImporter.alphaIsTransparency = true;
            texImporter.convertToNormalmap  = false;
            texImporter.grayscaleToAlpha    = false;
            texImporter.lightmap            = false;
            texImporter.npotScale           = TextureImporterNPOTScale.None;
            texImporter.filterMode          = FilterMode.Point;
            texImporter.wrapMode            = TextureWrapMode.Clamp;
            texImporter.maxTextureSize      = 4096;
            texImporter.mipmapEnabled       = false;
            texImporter.textureFormat       = TextureImporterFormat.AutomaticTruecolor;
            AssetDatabase.ImportAsset(textureName, ImportAssetOptions.ForceUpdate);

            tex.filterMode = FilterMode.Bilinear;
            tex.wrapMode   = TextureWrapMode.Clamp;

            textures.Add(tex);

#if RSATLASHELPER_DEBUG
            Debug.Log("- added tex: " + textureName);
#endif
        }

        List <UIAtlasMaker.SpriteEntry> sprites = UIAtlasMaker.CreateSprites(textures);
        UIAtlasMaker.ExtractSprites(newAtlas, sprites);
        UIAtlasMaker.UpdateAtlas(newAtlas, sprites);
        AssetDatabase.SaveAssets();

        {
            string resourceDir = GetAtlasResourceFolder(device, atlasType);
            string atlasName2  = GetAtlasName(atlasName, device, atlasType);
            string newTex      = "Assets" + resourceDir + atlasName2 + ".png";

            TextureImporter texImporter    = AssetImporter.GetAtPath(newTex) as TextureImporter;
            int             maxTextureSize = atlasType == AtlasType.HD ? 4096 : 2048;
            texImporter.maxTextureSize = maxTextureSize;
            texImporter.textureFormat  = TextureImporterFormat.AutomaticCompressed;
            if (device == Device.Phone)
            {
                texImporter.mipmapEnabled = true;
                texImporter.borderMipmap  = true;
                texImporter.mipmapFilter  = TextureImporterMipFilter.BoxFilter;
            }
            else
            {
                texImporter.mipmapEnabled = false;
            }
            texImporter.alphaIsTransparency = true;
            texImporter.filterMode          = FilterMode.Bilinear;
            texImporter.wrapMode            = TextureWrapMode.Clamp;
            texImporter.anisoLevel          = 1;
            texImporter.SetPlatformTextureSettings("iPhone", maxTextureSize, TextureImporterFormat.PVRTC_RGBA4);
            texImporter.SetPlatformTextureSettings("Android", maxTextureSize, TextureImporterFormat.PVRTC_RGBA4);
            AssetDatabase.ImportAsset(newTex, ImportAssetOptions.ForceUpdate);
        }

        UpdateAtlasSpriteData(ref newAtlas, ref oldSpriteData);

#if RSATLASHELPER_DEBUG
        DebugAtlasSpriteData(ref newAtlas);
#endif

        newAtlas.MarkAsChanged();
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        return(newAtlas);
    }
예제 #21
0
	/// <summary>
	/// Update the sprite atlas, keeping only the sprites that are on the specified list.
	/// </summary>

	static public void UpdateAtlas (UIAtlas atlas, List<SpriteEntry> sprites)
	{
		if (sprites.Count > 0)
		{
			// Combine all sprites into a single texture and save it
			if (UpdateTexture(atlas, sprites))
			{
				// Replace the sprites within the atlas
				ReplaceSprites(atlas, sprites);
			}

			// Release the temporary textures
			ReleaseSprites(sprites);
			EditorUtility.ClearProgressBar();
			return;
		}
		else
		{
			atlas.spriteList.Clear();
			string path = NGUIEditorTools.GetSaveableTexturePath(atlas);
			atlas.spriteMaterial.mainTexture = null;
			if (!string.IsNullOrEmpty(path)) AssetDatabase.DeleteAsset(path);
		}

		atlas.MarkAsChanged();
		Selection.activeGameObject = (NGUISettings.atlas != null) ? NGUISettings.atlas.gameObject : null;
		EditorUtility.ClearProgressBar();
	}
예제 #22
0
	/// <summary>
	/// Replace the sprites within the atlas.
	/// </summary>

	static public void ReplaceSprites (UIAtlas atlas, List<SpriteEntry> sprites)
	{
		// Get the list of sprites we'll be updating
		List<UISpriteData> spriteList = atlas.spriteList;
		List<UISpriteData> kept = new List<UISpriteData>();

		// Run through all the textures we added and add them as sprites to the atlas
		for (int i = 0; i < sprites.Count; ++i)
		{
			SpriteEntry se = sprites[i];
			UISpriteData sprite = AddSprite(spriteList, se);
			kept.Add(sprite);
		}

		// Remove unused sprites
		for (int i = spriteList.Count; i > 0; )
		{
			UISpriteData sp = spriteList[--i];
			if (!kept.Contains(sp)) spriteList.RemoveAt(i);
		}

		// Sort the sprites so that they are alphabetical within the atlas
		atlas.SortAlphabetically();
		atlas.MarkAsChanged();
	}
예제 #23
0
    /// <summary>
    /// Mark all widgets associated with this atlas as having changed.
    /// </summary>

    public void MarkAsChanged()
    {
#if UNITY_EDITOR
        NGUITools.SetDirty(gameObject);
#endif
        if (mReplacement != null)
        {
            mReplacement.MarkAsChanged();
        }

        UISprite[] list = NGUITools.FindActive <UISprite>();

        for (int i = 0, imax = list.Length; i < imax; ++i)
        {
            UISprite sp = list[i];

            if (CheckIfRelated(this, sp.atlas))
            {
                UIAtlas atl = sp.atlas;
                sp.atlas = null;
                sp.atlas = atl;
#if UNITY_EDITOR
                NGUITools.SetDirty(sp);
#endif
            }
        }

        UIFont[] fonts = Resources.FindObjectsOfTypeAll(typeof(UIFont)) as UIFont[];

        for (int i = 0, imax = fonts.Length; i < imax; ++i)
        {
            UIFont font = fonts[i];

            if (CheckIfRelated(this, font.atlas))
            {
                UIAtlas atl = font.atlas;
                font.atlas = null;
                font.atlas = atl;
#if UNITY_EDITOR
                NGUITools.SetDirty(font);
#endif
            }
        }

        UILabel[] labels = NGUITools.FindActive <UILabel>();

        for (int i = 0, imax = labels.Length; i < imax; ++i)
        {
            UILabel lbl = labels[i];

            if (lbl.bitmapFont != null && CheckIfRelated(this, lbl.bitmapFont.atlas))
            {
                UIFont font = lbl.bitmapFont;
                lbl.bitmapFont = null;
                lbl.bitmapFont = font;
#if UNITY_EDITOR
                NGUITools.SetDirty(lbl);
#endif
            }
        }
    }
예제 #24
0
    private void OnGUI()
    {
        GUILayout.BeginVertical();
        // 绘制作者信息
        NIEditorUtility.DrawAuthorSummary();
        GUILayout.Space(5);
        if (GUILayout.Button("刷新", GUILayout.MaxWidth(70)))
        {
            Refresh();
            return;
        }
        GUILayout.Space(5);
        GUILayout.EndVertical();

        GUILayout.BeginHorizontal();
        GUILayout.BeginVertical();
        GUI.backgroundColor = new Color32(150, 200, 255, 255);
        //未创建的在前,已创建的在后
        dirList.Sort((string a, string b) =>
        {
            string aPath = a.Replace("Z_RES/Atlas/", "Assets/Art/Atlas/");
            string bPath = b.Replace("Z_RES/Atlas/", "Assets/Art/Atlas/");
            bool ae      = Directory.Exists(aPath);
            bool be      = Directory.Exists(bPath);
            if (ae && !be)
            {
                return(1);
            }
            else if (!ae && be)
            {
                return(-1);
            }
            else
            {
                //GetFileNameWithoutExtension得到没有扩充名(.txt)的文件名
                //按首字母排序
                string aN = Path.GetFileNameWithoutExtension(a);
                string bN = Path.GetFileNameWithoutExtension(b);
                return(aN[0] - bN[0]);
            }
        });

        //文件夹列表
        scrollPos = GUILayout.BeginScrollView(scrollPos, "AS TextArea", GUILayout.Width(480), GUILayout.Height(600));
        for (int i = 0; i < dirList.Count; i++)
        {
            string atlasName = Path.GetFileNameWithoutExtension(dirList[i]);

            GUILayout.BeginHorizontal();
            GUILayout.Space(10f);
            string resPath   = dirList[i].Replace("Z_RES/Atlas/", "Assets/Art/Atlas/");
            string buttonTxt = "";
            bool   isNew     = false;
            if (Directory.Exists(resPath))
            {
                buttonTxt = "更新";
            }
            else
            {
                buttonTxt = "创建";
                isNew     = true;
            }

            if (isNew)
            {
                GUI.color = Color.green;
            }

            //1.创建/更新按钮
            if (GUILayout.Button(buttonTxt, GUILayout.Width(50), GUILayout.Height(20)))
            {
                MakeAtlas(atlasName);
            }

            if (isNew)
            {
                GUI.color = Color.white;
            }

            //2.文件夹名
            GUILayout.Label(atlasName, EditorStyles.boldLabel);

            //3.配置文件按钮
            if (!isNew)
            {
                if (GUILayout.Button("配置", GUILayout.Width(70f), GUILayout.Height(20)))
                {
                    if (File.Exists(ATLAS_PREFAB_PATH + atlasName + "Atlas" + ".prefab"))
                    {
                        UIAtlas atlas    = Resources.Load <UIAtlas>("Atlas/" + atlasName + "Atlas");
                        string  textPath = ATLAS_PATH + atlasName + ".txt";
                        textPath = GetProjectRelativePath(textPath);

                        TextAsset configuration = AssetDatabase.LoadAssetAtPath <TextAsset>(textPath);
                        NGUIJson.LoadSpriteData(atlas, configuration); //装载图集配置文件
                        atlas.MarkAsChanged();
                        PrefabUtility.RecordPrefabInstancePropertyModifications(atlas);
                    }
                }
            }

            GUILayout.EndHorizontal();
            GUILayout.Space(10f);
        }
        GUILayout.EndScrollView();

        GUI.backgroundColor = Color.white;
        GUILayout.Space(10f);
        GUILayout.EndVertical();
        GUILayout.EndHorizontal();
    }
예제 #25
0
    /// <summary>
    /// Mark all widgets associated with this atlas as having changed.
    /// </summary>

    public void MarkAsChanged()
    {
#if UNITY_EDITOR
        var args      = Environment.GetCommandLineArgs();
        var batchmode = false;
        foreach (var a in args)
        {
            if (a == "-batchmode")
            {
                batchmode = true;
            }
        }

        if (!batchmode)
        {
//            if(gameObject != null)
//		        NGUITools.SetDirty(gameObject);
        }
#endif
        if (mReplacement != null)
        {
            mReplacement.MarkAsChanged();
        }

        UISprite[] list = NGUITools.FindActive <UISprite>();

        for (int i = 0, imax = list.Length; i < imax; ++i)
        {
            UISprite sp = list[i];

            if (CheckIfRelated(this, sp.atlas))
            {
                UIAtlas atl = sp.atlas;
                sp.atlas = null;
                sp.atlas = atl;
#if UNITY_EDITOR
                NGUITools.SetDirty(sp);
#endif
            }
        }

        UIFont[] fonts = Resources.FindObjectsOfTypeAll(typeof(UIFont)) as UIFont[];

        for (int i = 0, imax = fonts.Length; i < imax; ++i)
        {
            UIFont font = fonts[i];

            if (CheckIfRelated(this, font.atlas))
            {
                UIAtlas atl = font.atlas;
                font.atlas = null;
                font.atlas = atl;
#if UNITY_EDITOR
                NGUITools.SetDirty(font);
#endif
            }
        }

        UILabel[] labels = NGUITools.FindActive <UILabel>();

        for (int i = 0, imax = labels.Length; i < imax; ++i)
        {
            UILabel lbl = labels[i];

            if (lbl.bitmapFont != null && CheckIfRelated(this, lbl.bitmapFont.atlas))
            {
                UIFont font = lbl.bitmapFont;
                lbl.bitmapFont = null;
                lbl.bitmapFont = font;
#if UNITY_EDITOR
                NGUITools.SetDirty(lbl);
#endif
            }
        }
    }
예제 #26
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        GUILayout.Space(18f);
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        if (mat != null)
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }

            if (NGUIEditorTools.DrawHeader("Scale Factor"))
            {
                NGUIEditorTools.BeginContents();
                {
                    EditorGUILayout.HelpBox(
                        "If the image size(pixel size in photoshop) is not equal to texture size(pixel size in unity), you should set the scale factor to help NGUI to adjust uv.",
                        MessageType.Info, true
                        );

                    EditorGUILayout.HelpBox(
                        "You should click the the button below to recalculate scale factor for atlas when the atlas' texture is changed. For example, when you add sprite, remove sprite, set compressed format or change maxsize etc.",
                        MessageType.Warning, true
                        );

                    if (GUILayout.Button("Calculate Scale Factor Automatically"))
                    {
                        if (mAtlas.texture != null)
                        {
                            string path     = AssetDatabase.GetAssetPath(mAtlas.texture);
                            string fullPath = Application.dataPath + path.Substring("Assets".Length);
                            if (File.Exists(fullPath))
                            {
                                MemoryStream memoryStream = null;
                                BinaryReader binaryReader = null;
                                try
                                {
                                    byte[] bytes = File.ReadAllBytes(fullPath);
                                    memoryStream = new MemoryStream(bytes);
                                    binaryReader = new BinaryReader(memoryStream);
                                    // Is PNG
                                    if (binaryReader.ReadByte() == 0x89 && binaryReader.ReadByte() == 0x50 && binaryReader.ReadByte() == 0x4E &&
                                        binaryReader.ReadByte() == 0x47 && binaryReader.ReadByte() == 0x0D && binaryReader.ReadByte() == 0x0A &&
                                        binaryReader.ReadByte() == 0x1A && binaryReader.ReadByte() == 0x0A)
                                    {
                                        binaryReader.ReadUInt32();
                                        binaryReader.ReadUInt32();
                                        uint            width           = LittleEndianToBigEndian(binaryReader.ReadUInt32());
                                        uint            height          = LittleEndianToBigEndian(binaryReader.ReadUInt32());
                                        TextureImporter textureImporter = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(mAtlas.texture));

                                        System.Action <string, UIAtlas.SCALE_PLATFORM, BuildTarget> processScale = delegate(string platformName, UIAtlas.SCALE_PLATFORM platformAtlasEnum, BuildTarget platformEnum)
                                        {
                                            if (mAtlas.scales == null || mAtlas.scales.Length != (int)UIAtlas.SCALE_PLATFORM.SIZE * 2)
                                            {
                                                mAtlas.scales = new float[(int)UIAtlas.SCALE_PLATFORM.SIZE * 2] {
                                                    1, 1, 1, 1, 1, 1, 1, 1, 1, 1
                                                };
                                            }

                                            //      TextureImportInstructions info = new TextureImportInstructions();
                                            //      textureImporter.ReadTextureImportInstructions(info, platformEnum);
                                            int maxSize;
                                            TextureImporterFormat format;
                                            if (textureImporter.GetPlatformTextureSettings(platformName, out maxSize, out format))
                                            {
                                                float len = width > height ? width : height;
                                                mAtlas.scales[(int)platformAtlasEnum * 2]     = len / (float)width;
                                                mAtlas.scales[(int)platformAtlasEnum * 2 + 1] = len / (float)height;
                                            }
                                            else
                                            {
                                                mAtlas.scales[(int)platformAtlasEnum * 2]     = 1;
                                                mAtlas.scales[(int)platformAtlasEnum * 2 + 1] = 1;
                                            }
                                        };

                                        processScale("Web", UIAtlas.SCALE_PLATFORM.WEB, BuildTarget.WebPlayer);
                                        processScale("Standalone", UIAtlas.SCALE_PLATFORM.STANDALONE, BuildTarget.StandaloneWindows);
                                        processScale("iPhone", UIAtlas.SCALE_PLATFORM.IPHONE, BuildTarget.iOS);
                                        processScale("Android", UIAtlas.SCALE_PLATFORM.ANDROID, BuildTarget.Android);

                                        NGUITools.SetDirty(mAtlas);
                                    }
                                }
                                catch (System.Exception exception)
                                {
                                    Debug.LogError(exception.StackTrace);
                                    UnityEditor.EditorUtility.DisplayDialog("Error", "Error:Set the scale factor mamually.", "ok");
                                }
                                finally
                                {
                                    if (memoryStream != null)
                                    {
                                        memoryStream.Close();
                                        memoryStream.Dispose();
                                        memoryStream = null;
                                    }
                                    if (binaryReader != null)
                                    {
                                        binaryReader.Close();
                                        binaryReader = null;
                                    }
                                }
                            }
                            else
                            {
                                UnityEditor.EditorUtility.DisplayDialog("Alert", "File is not exists\n" + fullPath, "ok");
                            }
                        }
                        else
                        {
                            UnityEditor.EditorUtility.DisplayDialog("Alert", "Null Texture", "ok");
                        }
                    }
                }
                NGUIEditorTools.EndContents();
            }
        }

        if (mAtlas.spriteMaterial != null)
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
                if (sprite == null)
                {
                    sprite = mAtlas.spriteList[0];
                }
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

                Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

                if (tex != null)
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        UIAtlasMaker.SpriteEntry se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
                        if (se != null)
                        {
                            NGUISettings.selectedSprite = se.name;
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
                        string path = EditorUtility.SaveFilePanelInProject("Save As", sprite.name + ".png", "png", "Extract sprite into which file?");

                        if (!string.IsNullOrEmpty(path))
                        {
                            UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                byte[] bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        GUILayout.Space(18f);
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                UnityEditor.EditorUtility.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        if (mat != null)
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null)
        {
            Color blue  = new Color(0f, 0.7f, 1f, 1f);
            Color green = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
                if (sprite == null)
                {
                    sprite = mAtlas.spriteList[0];
                }
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

                Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

                if (tex != null)
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = green;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blue;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
예제 #28
0
    void OnInspectorUpdate()
    {
        bool refresh = false;

        switch (retinaProState.state)
        {
        default:
        case retinaProState.rpState.kWaiting:
            break;

        case retinaProState.rpState.kGen:
        {
            deviceIndex    = 0;
            fileIndex      = 0;
            progressPeriod = 0.0f;
            progressString = "Atlas " + genAtlasItem.atlasName;

#if RETINAPRO_DEBUGLOG
            Debug.Log(progressString);
#endif

            if (genAtlasItem.isFont)
            {
                retinaProState.state = retinaProState.rpState.kFont;
            }
            else
            {
                // create atlas that will be used as the reference for the device specific atlas
                UIAtlas atlasRef = retinaProNGTools.createAtlas(genAtlasItem.atlasName, null, out oldSpriteData);
                oldSpriteData = null;
                if (atlasRef == null)
                {
                    Debug.LogWarning("Could not create atlas reference for " + genAtlasItem.atlasName);
                    retinaProState.state = retinaProState.rpState.kDone;
                    break;
                }

                retinaProParent parent = atlasRef.gameObject.GetComponent <retinaProParent>();
                if (parent == null)
                {
                    atlasRef.gameObject.AddComponent <retinaProParent>();
                }

                EditorUtility.SetDirty(atlasRef.gameObject);
                retinaProState.state = retinaProState.rpState.kAtlas;
            }

            break;
        }


        case retinaProState.rpState.kAtlas: {
            retinaProDevice deviceItem = retinaProDataSerialize.sharedInstance.deviceList[deviceIndex];
            progressString       = "Atlas " + genAtlasItem.atlasName + " / " + deviceItem.name + " - Processing images";
            retinaProState.state = retinaProState.rpState.kAtlasProcess;
            break;
        }


        case retinaProState.rpState.kAtlasProcess: {
            retinaProDevice deviceItem = retinaProDataSerialize.sharedInstance.deviceList[deviceIndex];

#if RETINAPRO_DEBUGLOG
            Debug.Log("addNewAtlas; " + genAtlasItem.atlasName + ", for device: " + deviceItem.name + ", pixelSize = " + deviceItem.pixelSize);
#endif
            // gather textures for this atlas / device
            DirectoryInfo dinfo = new DirectoryInfo(retinaProFileLock.baseDataPath + retinaProConfig.atlasTextureFolder + deviceItem.name + "/" + genAtlasItem.atlasName);
            if (dinfo == null || !dinfo.Exists)
            {
                Debug.LogWarning("Folder does not exist; " + genAtlasItem.atlasName + ", for device: " + deviceItem.name + ", pixelSize = " + deviceItem.pixelSize);
            }
            else
            {
                List <FileInfo> fis;
                retinaProConfig.getValidArtFiles(dinfo, out fis);

                if (fis != null && fis.Count > 0)
                {
                    genAtlas = retinaProNGTools.createAtlas(genAtlasItem.atlasName, deviceItem.name, out oldSpriteData);
                    if (genAtlas == null)
                    {
                        Debug.LogWarning("Could not create atlas for " + genAtlasItem.atlasName + ", device = " + deviceItem.name);
                        retinaProState.state = retinaProState.rpState.kDone;
                        break;
                    }

                    NGUISettings.atlas         = genAtlas;
                    NGUISettings.atlasPadding  = genAtlasItem.atlasPadding;
                    NGUISettings.atlasTrimming = false;
                    NGUISettings.allow4096     = true;
                    NGUISettings.fontTexture   = null;
                    NGUISettings.unityPacking  = true;

                    genAtlas.pixelSize = deviceItem.pixelSize;
                    EditorUtility.SetDirty(genAtlas.gameObject);

                    // add all art files into the atlas (one-pass)
                    List <Texture> textures = new List <Texture>();

                    foreach (FileInfo fi in fis)
                    {
                        // check to see if this file has a corresponding .txt file (i.e. it's a font)
                        bool isFont = false;
                        {
                            string fontName = Path.GetFileNameWithoutExtension(fi.Name);
                            if (dinfo != null && dinfo.Exists)
                            {
                                FileInfo [] fontTextFile = dinfo.GetFiles(fontName + ".txt");
                                if (fontTextFile != null && fontTextFile.Length == 1)
                                {
                                    isFont = true;
                                }
                            }
                        }

                        if (isFont)
                        {
                            progressString = "Atlas " + genAtlasItem.atlasName + " / " + deviceItem.name + " - Fonts in a sprite atlas are not supported!";
                            string fontName = Path.GetFileNameWithoutExtension(fi.Name);
                            Debug.LogWarning("Fonts (" + fontName + ") in a sprite atlas is not supported. Use a font atlas instead, see the example scene.");
                        }
                        else
                        {
                            {
                                string textureName = "Assets" + retinaProConfig.atlasTextureFolder + deviceItem.name + "/" + genAtlasItem.atlasName + "/" + fi.Name;

                                // source texture
                                Texture2D tex = AssetDatabase.LoadAssetAtPath(textureName, typeof(Texture2D)) as Texture2D;
                                if (retinaProDataSerialize.sharedInstance.getUtilityRefreshSourceTextures())                                            // refresh importer settings on source texture?
                                // update texture importer settings on source artwork
                                // this ensures that we don't bring in assets into the atlas that are too small (for their given size)
                                {
                                    TextureImporter tImporter = AssetImporter.GetAtPath(textureName) as TextureImporter;
                                    if (tImporter != null)
                                    {
                                        tImporter.textureType         = TextureImporterType.Advanced;
                                        tImporter.normalmap           = false;
                                        tImporter.linearTexture       = true;
                                        tImporter.alphaIsTransparency = true;
                                        tImporter.convertToNormalmap  = false;
                                        tImporter.grayscaleToAlpha    = false;
                                        tImporter.lightmap            = false;
                                        tImporter.npotScale           = TextureImporterNPOTScale.None;
                                        tImporter.filterMode          = FilterMode.Point;
                                        tImporter.maxTextureSize      = 4096;
                                        tImporter.mipmapEnabled       = false;
                                        tImporter.textureFormat       = TextureImporterFormat.AutomaticTruecolor;
                                        AssetDatabase.ImportAsset(textureName, ImportAssetOptions.ForceUpdate);
                                    }
                                }

                                tex.filterMode = genAtlasItem.atlasFilterMode;
                                tex.wrapMode   = TextureWrapMode.Clamp;
                                textures.Add(tex);

#if RETINAPRO_DEBUGLOG
                                Debug.Log("- added tex: " + textureName);
#endif
                            }
                        }
                    }

                    List <UIAtlasMaker.SpriteEntry> sprites = UIAtlasMaker.CreateSprites(textures);
                    UIAtlasMaker.ExtractSprites(genAtlas, sprites);
                    UIAtlasMaker.UpdateAtlas(genAtlas, sprites);
                    AssetDatabase.SaveAssets();

                    // set texture filter mode
                    {
                        string          newTex    = "Assets" + retinaProConfig.atlasResourceFolder + deviceItem.name + "/" + genAtlasItem.atlasName + "~" + deviceItem.name + ".png";
                        TextureImporter tImporter = AssetImporter.GetAtPath(newTex) as TextureImporter;

                        if (tImporter != null)
                        {
                            tImporter.filterMode    = genAtlasItem.atlasFilterMode;
                            tImporter.textureFormat = genAtlasItem.atlasTextureFormat;
                            AssetDatabase.ImportAsset(newTex, ImportAssetOptions.ForceUpdate);
                        }
                    }

                    // restore the sprite data within the atlas
                    // update the new atlas with the old sprite data
                    retinaProNGTools.updateAtlasSpriteData(ref genAtlas, ref oldSpriteData);
#if RETINAPRO_DEBUGLOG
                    retinaProNGTools.debugAtlasSpriteData(ref genAtlas);
#endif

                    genAtlas.MarkAsChanged();
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();


                    // continue with next device
                    deviceIndex++;
                    if (deviceIndex >= retinaProDataSerialize.sharedInstance.deviceList.Count)
                    {
                        retinaProState.state = retinaProState.rpState.kDone;
                        break;
                    }
                    else
                    {
                        retinaProState.state = retinaProState.rpState.kAtlas;
                    }

                    progressPortion = 0.0f;
                    break;
                }
            }
            break;
        }

        case retinaProState.rpState.kFont:
        {
            retinaProDevice deviceItem = retinaProDataSerialize.sharedInstance.deviceList[deviceIndex];

            DirectoryInfo dinfo = new DirectoryInfo(retinaProFileLock.baseDataPath + retinaProConfig.atlasTextureFolder + deviceItem.name + "/" + genAtlasItem.atlasName);
            if (dinfo == null || !dinfo.Exists)
            {
                Debug.LogWarning("Folder does not exist; " + genAtlasItem.atlasName + ", for device: " + deviceItem.name + ", pixelSize = " + deviceItem.pixelSize);
                retinaProState.state = retinaProState.rpState.kDone;
                break;
            }

            FileInfo [] fis    = dinfo.GetFiles("*.png");
            FileInfo [] fisTxt = dinfo.GetFiles("*.txt");

            if (fis == null || fis.Length != 1 || fisTxt == null || fisTxt.Length != 1)
            {
                Debug.LogWarning("Font atlases should contain two files; thefont.png / thefont.txt");
                fileIndex            = fis.Length;
                retinaProState.state = retinaProState.rpState.kDone;
                break;
            }

            FileInfo fi = fis[fileIndex];

            {
                string fontName = Path.GetFileNameWithoutExtension(fi.Name);
                progressString = "Atlas " + genAtlasItem.atlasName + " / " + deviceItem.name + " / " + fontName;

#if RETINAPRO_DEBUGLOG
                Debug.Log("addNewFont; " + fontName + ", for device: " + deviceItem.name + ", pixelSize = " + deviceItem.pixelSize);
#endif

                UIFont font = retinaProNGTools.createFont(genAtlasItem.atlasName, fontName, deviceItem.name);
                //font.pixelSize = deviceItem.pixelSize;
                EditorUtility.SetDirty(font.gameObject);

                // create the reference font version
                UIFont fontRef = retinaProNGTools.createFont(genAtlasItem.atlasName, fontName, null);
                fontRef.replacement = font;
                //fontRef.pixelSize = deviceItem.pixelSize;

                retinaProParent parent = fontRef.gameObject.GetComponent <retinaProParent>();
                if (parent == null)
                {
                    fontRef.gameObject.AddComponent <retinaProParent>();
                }

                EditorUtility.SetDirty(fontRef.gameObject);
            }

            // set texture filter mode
            {
                string          newTex    = "Assets" + retinaProConfig.atlasTextureFolder + deviceItem.name + "/" + genAtlasItem.atlasName + "/" + fis[0].Name;
                TextureImporter tImporter = AssetImporter.GetAtPath(newTex) as TextureImporter;

                if (tImporter != null)
                {
                    tImporter.filterMode    = genAtlasItem.atlasFilterMode;
                    tImporter.textureFormat = genAtlasItem.atlasTextureFormat;
                    AssetDatabase.ImportAsset(newTex, ImportAssetOptions.ForceUpdate);
                }
            }


            fileIndex++;
            if (fileIndex >= fis.Length)
            {
                fileIndex = 0;

                deviceIndex++;
                if (deviceIndex >= retinaProDataSerialize.sharedInstance.deviceList.Count)
                {
                    fileIndex            = fis.Length;
                    retinaProState.state = retinaProState.rpState.kDone;
                }
            }
            progressPortion = (((float)(fileIndex + 1)) / ((float)fis.Length));
            progressPortion = Mathf.Clamp01(progressPortion);
            break;
        }

        case retinaProState.rpState.kDone:
        {
            EditorUtility.ClearProgressBar();
            refresh = true;
            retinaProState.state = retinaProState.rpState.kWaiting;
            Repaint();
            break;
        }
        }

        if (refresh)
        {
#if RETINAPRO_DEBUGLOG
            Debug.Log("refresh called");
#endif
            int             idx = retinaProDataSerialize.sharedInstance.getPreviewDeviceIdx();
            retinaProDevice di  = retinaProDataSerialize.sharedInstance.deviceList[idx];
            if (di.isDeviceValid())
            {
                retinaProNGTools.refreshReferencesForDevice(di, retinaProDataSerialize.sharedInstance.getPreviewScreenIdx(), retinaProDataSerialize.sharedInstance.getPreviewGameViewIdx());
                retinaProNGTools.refresh();
            }
        }

        if (retinaProState.state != retinaProState.rpState.kWaiting)
        {
            Repaint();
        }
    }
예제 #29
0
    /// <summary>
    /// 配置NGUI图集,srcFullPath是txt和png文件所在目录,绝对路径.atlasAssetPath是图集的目录,以Assets开头的路径
    /// </summary>
    private static void SetupNGUIAtlas(string srcFullPath, string atlasAssetPath)
    {
        try
        {
            AssetDatabase.Refresh();
            List <string> fileList = new List <string>();
            findFiles(srcFullPath, ref fileList, ".png", false);
            for (int i = 0; i < fileList.Count; ++i)
            {
                EditorUtility.DisplayProgressBar("设置NGUI图集", "正在进行" + getFileName(fileList[i]), i / (float)fileList.Count);

                createDir(atlasAssetPath);
                string assetNameNoSuffix = atlasAssetPath + "/" + getFileNameNoSuffix(fileList[i], true);
                string prefabFile        = assetNameNoSuffix + ".prefab";
                string matFile           = assetNameNoSuffix + ".mat";
                string destPNGFile       = assetNameNoSuffix + ".png";
                // 拷贝png文件
                copyFile(fileList[i], projectPathToFullPath(destPNGFile));
                AssetDatabase.Refresh();

                // 加载文件图集文件,如果不存则创建
                GameObject prefabAsset = AssetDatabase.LoadMainAssetAtPath(prefabFile) as GameObject;
                if (prefabAsset == null)
                {
                    GameObject temp = new GameObject();
                    prefabAsset = PrefabUtility.CreatePrefab(prefabFile, temp);
                    GameObject.DestroyImmediate(temp);
                }
                UIAtlas uiAtlas = prefabAsset.GetComponent <UIAtlas>();
                if (uiAtlas == null)
                {
                    uiAtlas = prefabAsset.AddComponent <UIAtlas>();
                }
                // 创建材质文件
                Material matAsset = AssetDatabase.LoadMainAssetAtPath(matFile) as Material;
                if (matAsset == null)
                {
                    matAsset = new Material(Shader.Find("NGUIDefault"));
                    AssetDatabase.CreateAsset(matAsset, matFile);
                }

                // 配置图集参数
                string    srcPNGFile = fullPathToProjectPath(fileList[i]);
                string    dataFile   = getFileNameNoSuffix(srcPNGFile) + ".txt";
                Texture2D pngAsset   = GetAtlasTexture(destPNGFile);
                TextAsset dataAsset  = AssetDatabase.LoadMainAssetAtPath(dataFile) as TextAsset;
                matAsset.SetTexture("_MainTex", pngAsset);
                uiAtlas.spriteMaterial = matAsset;
                NGUIJson.LoadSpriteData(uiAtlas, dataAsset);
                uiAtlas.MarkAsChanged();
                EditorUtility.SetDirty(uiAtlas);
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError("Error " + ex.ToString());
        }
        finally
        {
            EditorUtility.ClearProgressBar();
        }

        AssetDatabase.Refresh();
    }
예제 #30
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        #region         //add by chenbin
        if (mAtlas.isBorrowSpriteMode)
        {
            GUI.color = Color.green;
        }
        else
        {
            GUI.color = Color.white;
        }
        GUILayout.Label("\n===	=========================================");
        if (GUILayout.Button("说明"))
        {
            isShowBorrowModeDesc = !isShowBorrowModeDesc;
        }
        if (isShowBorrowModeDesc)
        {
            GUILayout.Label("勾选isBorrowSpriteMode时,表明该atlas是空atlas,\n" +
                            "当有sprit对象来borrow时,atlas会根据名字从\n" +
                            "设置的路径中去取得图片资源。\n" +
                            //"其中资源必须在Resources/下,\n" +
                            "另外atlas必须要引用一个material,\n" +
                            "就算引用的是个空material也行。\n");
        }

        if (mAtlas != null && runTimes == 0)
        {
            runTimes++;
            isBorrowMode = mAtlas.isBorrowSpriteMode;
            //			isUserUnity3DType = mAtlas.useUnity3DType;
        }
        mAtlas.isBorrowSpriteMode = EditorGUILayout.Toggle("isBorrowSpriteMode", mAtlas.isBorrowSpriteMode);
        if (isBorrowMode != mAtlas.isBorrowSpriteMode)
        {
            isBorrowMode = mAtlas.isBorrowSpriteMode;
            UnityEditor.EditorUtility.SetDirty(mAtlas.gameObject);
        }
        //		if (mAtlas.isBorrowSpriteMode) {
        //			mAtlas.useUnity3DType = EditorGUILayout.Toggle ("useUnity3DType", mAtlas.useUnity3DType);
        //			if (isUserUnity3DType != mAtlas.useUnity3DType) {
        //				isUserUnity3DType = mAtlas.useUnity3DType;
        //				UnityEditor.EditorUtility.SetDirty (NGUISettings.atlas.gameObject);
        //			}
        //		}
        GUILayout.Label("============================================\n");
        GUI.color = Color.white;
        if (GUILayout.Button("Clean items if no png"))
        {
            if (EditorUtility.DisplayDialog("Alert", "Really ?", "Do it now!", "NO"))
            {
                UISpriteData        item = null;
                List <UISpriteData> list = new List <UISpriteData> ();
                for (int i = 0; i < mAtlas.spriteList.Count; i++)
                {
                    item = mAtlas.spriteList [i];
                    string path = Application.dataPath + "/" + item.path;
                    path = path.Replace("/upgradeRes/", "/upgradeRes4Dev/");
                    path = path.Replace("/upgradeRes4Publish/", "/upgradeRes4Dev/");
                    if (!File.Exists(path))
                    {
                        Debug.Log(path);
                        list.Add(item);
                    }
                }
                deleteSprites(list);
            }
        }
        #endregion                                    //end ======add by chenbin

        if (mat != null || mAtlas.isBorrowSpriteMode) // modify by chenbin
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null || mAtlas.isBorrowSpriteMode)                 //modify by chenbin
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
//				if (sprite == null) sprite = mAtlas.spriteList[0];  // delete by chenbin
                #region add by chenbin
                if (sprite == null)
                {
                    if (mAtlas.isBorrowSpriteMode)
                    {
                        sprite     = mAtlas.spriteList [0];
                        spriteName = sprite.name;
                        sprite     = mAtlas.borrowSpriteByname(spriteName, null);
                    }
                    else
                    {
                        sprite = mAtlas.spriteList [0];
                    }
                }
                #endregion
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

//				Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;	//delete by chenbin
                #region add by chenbin
                Texture2D tex = null;
                if (mAtlas != null)
                {
                    if (mAtlas.isBorrowSpriteMode)
                    {
                        if (sprite != null && sprite.material != null)
                        {
                            tex = sprite.material.mainTexture as Texture2D;
                        }
                    }
                    else
                    {
                        tex = mAtlas.spriteMaterial.mainTexture as Texture2D;
                    }
                }
                #endregion


//				if (tex != null)		//modify by chenbin
                if (tex != null || (mAtlas != null && mAtlas.isBorrowSpriteMode && sprite != null))                  //modify by chenbin
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        string newName = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);                         // modify by chenbin
                        if (newName != null)
                        {
                            NGUISettings.selectedSprite = newName;                                              // modify by chenbin
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
#if UNITY_3_5
                        string path = EditorUtility.SaveFilePanel("Save As",
                                                                  NGUISettings.currentPath, sprite.name + ".png", "png");
#else
                        string path = EditorUtility.SaveFilePanelInProject("Save As",
                                                                           sprite.name + ".png", "png",
                                                                           "Extract sprite into which file?", NGUISettings.currentPath);
#endif

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                byte[] bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
예제 #31
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        if (mat != null)
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null)
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
                if (sprite == null)
                {
                    sprite = mAtlas.spriteList[0];
                }
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

                Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

                if (tex != null)
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        UIAtlasMaker.SpriteEntry se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
                        if (se != null)
                        {
                            NGUISettings.selectedSprite = se.name;
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
                        string path = EditorUtility.SaveFilePanel("Save As",
                                                                  NGUISettings.currentPath, sprite.name + ".png", "png");

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                byte[] bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    if (GUILayout.Button("Save As All"))
                    {
                        string path = EditorUtility.SaveFolderPanel("Save As All",
                                                                    NGUISettings.currentPath, "");
                        if (!string.IsNullOrEmpty(path))
                        {
                            var list = mAtlas.spriteList;
                            foreach (var uiSpriteData in list)
                            {
                                var spName = uiSpriteData.name;
                                NGUISettings.currentPath = path;
                                UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, spName);
                                if (se != null)
                                {
                                    var    filePath = string.Format("{0}/{1}.png", path, spName);
                                    byte[] bytes    = se.tex.EncodeToPNG();
                                    File.WriteAllBytes(filePath, bytes);
                                    AssetDatabase.ImportAsset(filePath);
                                    if (se.temporaryTexture)
                                    {
                                        DestroyImmediate(se.tex);
                                    }
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
예제 #32
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        if (mat != null)
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null)
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
                if (sprite == null)
                {
                    sprite = mAtlas.spriteList[0];
                }
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

                Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

                if (tex != null)
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        UIAtlasMaker.SpriteEntry se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
                        if (se != null)
                        {
                            NGUISettings.selectedSprite = se.name;
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
#if UNITY_3_5
                        string path = EditorUtility.SaveFilePanel("Save As",
                                                                  NGUISettings.currentPath, sprite.name + ".png", "png");
#else
                        string path = EditorUtility.SaveFilePanelInProject("Save As",
                                                                           sprite.name + ".png", "png",
                                                                           "Extract sprite into which file?", NGUISettings.currentPath);
#endif

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                byte[] bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }

                if (NGUIEditorTools.DrawHeader("Texture Optimization"))
                {
                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);

                    EditorGUILayout.BeginHorizontal();
                    NGUIEditorTools.DrawPadding();
                    TextureCompressionQuality afterType = (TextureCompressionQuality)EditorGUILayout.EnumPopup("Quality Type", NGUIEditorTools.mTextureType);
                    NGUIEditorTools.DrawPadding();

                    if (afterType != NGUIEditorTools.mTextureType)
                    {
                        NGUIEditorTools.mTextureType = afterType;
                    }

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.BeginHorizontal();

                    NGUIEditorTools.DrawPadding();

                    EditorGUILayout.BeginVertical();
                    EditorGUI.BeginDisabledGroup(mat.shader.name != "My Shaders/UITextureBinding");
                    if (GUILayout.Button("원본 사용"))
                    {
                        NGUIEditorTools.SetTextureOptimization(mAtlas, false);
                    }
                    EditorGUI.EndDisabledGroup();
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.BeginVertical();
                    EditorGUI.BeginDisabledGroup(mat.shader.name != "Unlit/Transparent Colored");
                    if (GUILayout.Button("최적화 사용"))
                    {
                        NGUIEditorTools.SetTextureOptimization(mAtlas, true);
                    }
                    EditorGUI.EndDisabledGroup();
                    EditorGUILayout.EndVertical();
                    NGUIEditorTools.DrawPadding();
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();
                    NGUIEditorTools.DrawPadding();
                    EditorGUILayout.BeginVertical();
                    if (GUILayout.Button("전체 원본으로"))
                    {
                        string[] aAtlasFiles = Directory.GetFiles("Assets/Resources/Prefabs/UI_Data/UI_Atlas", "*.prefab", SearchOption.AllDirectories);

                        for (int i = 0; i < aAtlasFiles.Length; ++i)
                        {
                            EditorUtility.DisplayProgressBar("Texture Optimization", "Combine...", ((i + 1) / (float)aAtlasFiles.Length));
                            UIAtlas sourceAtlas = (UIAtlas)AssetDatabase.LoadAssetAtPath(aAtlasFiles[i], typeof(UIAtlas)) as UIAtlas;

                            NGUIEditorTools.SetTextureOptimization(sourceAtlas, false);
                        }
                        EditorUtility.ClearProgressBar();
                    }
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.BeginVertical();

                    if (GUILayout.Button("전체 최적화"))
                    {
                        string[] aAtlasFiles = Directory.GetFiles("Assets/Resources/Prefabs/UI_Data/UI_Atlas", "*.prefab", SearchOption.AllDirectories);

                        for (int i = 0; i < aAtlasFiles.Length; ++i)
                        {
                            EditorUtility.DisplayProgressBar("Texture Optimization", string.Format("Devide..."), ((i + 1) / (float)aAtlasFiles.Length));

                            UIAtlas sourceAtlas = (UIAtlas)AssetDatabase.LoadAssetAtPath(aAtlasFiles[i], typeof(UIAtlas)) as UIAtlas;
                            shaderTextureBinding = shaderTextureBinding == null?Shader.Find("My Shaders/UITextureBinding") : shaderTextureBinding;

                            sourceAtlas.spriteMaterial.shader = shaderTextureBinding;
                            NGUIEditorTools.CopyAndChangeTexture(sourceAtlas, true);
                            sourceAtlas = (UIAtlas)AssetDatabase.LoadAssetAtPath(aAtlasFiles[i], typeof(UIAtlas)) as UIAtlas;
                            NGUIEditorTools.CopyAndChangeTexture(sourceAtlas, false);
                        }
                        EditorUtility.ClearProgressBar();
                    }
                    EditorGUILayout.EndVertical();
                    NGUIEditorTools.DrawPadding();
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.HelpBox("Quality Type : 텍스쳐의 Compression Quality (Best는 속도가 느리기 때문에 빌드할 때만 한다.)\n" +
                                            "원본, 최적화 사용 : 해당 아틀라스의 텍스쳐를 원본, 최적화 상태로 변경한다.\n" +
                                            "전체 원본, 전체 최적화 : UI_Atlas 폴더에 있는 모든 아틀라스를 일괄 원본, 최적화 상태로 변경한다.", MessageType.Info);

                    NGUIEditorTools.EndContents();
                }
            }
        }
    }
예제 #33
0
    //resName:文件夹名字->Common
    private void SetMeta(string resName)
    {
        string pngPath   = ATLAS_PATH + resName + "/" + resName + ".png";
        string alphaPath = ATLAS_PATH + resName + "/" + resName + "_alpha" + ".png";
        string textPath  = ATLAS_PATH + resName + "/" + resName + ".txt";

        pngPath   = GetProjectRelativePath(pngPath);
        alphaPath = GetProjectRelativePath(alphaPath);
        textPath  = GetProjectRelativePath(textPath);

        //设置图片属性
        TextureImporter texImp = AssetImporter.GetAtPath(pngPath) as TextureImporter;

        texImp.textureType = TextureImporterType.Default;
        //texImp.generateCubemap = TextureImporterGenerateCubemap.None;
        texImp.alphaIsTransparency = true;
        texImp.mipmapEnabled       = false;
        texImp.filterMode          = FilterMode.Bilinear;
        texImp.maxTextureSize      = 2048;
        //texImp.textureFormat = TextureImporterFormat.RGBA32;
        texImp.spriteImportMode = SpriteImportMode.None;
        texImp.SaveAndReimport();

        texImp             = AssetImporter.GetAtPath(alphaPath) as TextureImporter;
        texImp.textureType = TextureImporterType.Default;
        //texImp.generateCubemap = TextureImporterGenerateCubemap.None;
        texImp.alphaIsTransparency = false;
        texImp.spriteImportMode    = SpriteImportMode.None;
        texImp.filterMode          = FilterMode.Bilinear;
        texImp.mipmapEnabled       = false;
        texImp.maxTextureSize      = 2048;
        //texImp.textureFormat = TextureImporterFormat.Alpha8;
        texImp.SaveAndReimport();

        if (!File.Exists(ATLAS_PREFAB_PATH + resName + "Atlas" + ".prefab"))
        {
            //创建一个材质球并且配置好
            Shader   shader = Shader.Find("MyShader/two_tex_ui 1");
            Material mat    = new Material(shader);

            Texture texture     = AssetDatabase.LoadAssetAtPath <Texture>(pngPath);
            Texture alp_texture = AssetDatabase.LoadAssetAtPath <Texture>(alphaPath);
            mat.name = resName;
            mat.SetTexture("_MainTex", texture);
            texture = AssetDatabase.LoadAssetAtPath <Texture>(alphaPath);
            mat.SetTexture("_FlagTex", texture);
            AssetDatabase.CreateAsset(mat, GetProjectRelativePath(ATLAS_PATH + resName + "/" + resName + ".mat"));

            //创建一个预设体且配置好
            GameObject obj   = new GameObject();
            UIAtlas    atlas = obj.AddComponent <UIAtlas>();
            obj.name             = resName + "Atlas";
            atlas.spriteMaterial = mat;

            if (atlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(atlas.texture, false, false, !atlas.premultipliedAlpha);
            }
            atlas.MarkAsChanged();

            TextAsset ta = AssetDatabase.LoadAssetAtPath <TextAsset>(textPath);
            NGUIJson.LoadSpriteData(atlas, ta);
            atlas.MarkAsChanged();

            PrefabUtility.CreatePrefab(ATLAS_PREFAB_PATH + obj.name + ".prefab", obj, ReplacePrefabOptions.ReplaceNameBased);
            GameObject.DestroyImmediate(obj);
        }
    }