Inheritance: MonoBehaviour
Exemplo n.º 1
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="source">src attribute from img tag</param>
 /// <param name="fps">fps attribute from img tag</param>
 public NGUIImage(string source, int fps) {
   if ("#time".Equals(source, StringComparison.InvariantCultureIgnoreCase)) {
     isTime = true;
     timeFont = HtEngine.Device.LoadFont("code", 16, false, false, 0, 0);
   } else {
     string atlasName = source.Substring(0, source.LastIndexOf(':'));
     spriteName = source.Substring(source.LastIndexOf(':') + 1);
     isAnim = fps >= 0;
     FPS = fps;
    
     if (HtEngine.m_loadRes != null)
     {
         UnityEngine.GameObject _asset = HtEngine.m_loadRes(atlasName) as UnityEngine.GameObject;
         if (_asset != null)
         {
             uiAtlas = _asset.GetComponent<UIAtlas>();
         }
     }      
     else
     {
         uiAtlas = Resources.Load(atlasName, typeof(UIAtlas)) as UIAtlas;
     }
     if (uiAtlas == null)
     {
         Debug.LogWarning("Could not load html image atlas from " + atlasName + ":" + spriteName);
     }
   }
 }
Exemplo n.º 2
0
    public static float[] CalculateSprite(UIAtlas atlas, string name)
    {
        float[] output = new float[6];
        float left;
        float bottom;
        float width;
        float height;
        float UVHeight = 1f;
        float UVWidth = 1f;

        UIAtlas.Sprite sprite = atlas.GetSprite(name);
        if (sprite == null) {
            Debug.LogError("No sprite with that name: " + name);
            return null;
        }
        left = (int)sprite.inner.xMin;
        bottom = (int)sprite.inner.yMax;
        width = (int)sprite.inner.width;
        height = (int)sprite.inner.height;

        float widthHeightRatio = sprite.inner.width / sprite.inner.height;
        if (widthHeightRatio > 1)
            UVHeight = 1f / widthHeightRatio;       // It's a "wide" sprite
        else if (widthHeightRatio < 1)
            UVWidth = 1f * widthHeightRatio;        // It's a "tall" sprite

        output[0] = UVWidth;
        output[1] = UVHeight;
        output[2] = left;
        output[3] = bottom;
        output[4] = width;
        output[5] = height;

        return output;
    }
Exemplo n.º 3
0
 public bool VerifyValidAtlas(UIAtlas atlas)
 {
     if (atlas == currentCurrencyIcon.atlas)
         return true;
     else
         return false;
 }
Exemplo n.º 4
0
 void ChangeAtlas(UIAtlas currentAtlas)
 {
     if(spriteName != "")
         sprite.spriteName = spriteName;
     sprite.atlas = currentAtlas;
     sprite.MakePixelPerfect();
 }
Exemplo n.º 5
0
	/// <summary>
	/// Show the selection wizard.
	/// </summary>

	public static void Show (UIAtlas atlas, UISprite selectedSprite)
	{
		SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
		comp.mAtlas = atlas;
		comp.mSprite = selectedSprite;
		comp.mCallback = null;
	}
 public bool Validate(UIAtlas atlas)
 {
     if (atlas == null)
     {
         return false;
     }
     if (!this.mIsValid)
     {
         if (string.IsNullOrEmpty(this.spriteName))
         {
             return false;
         }
         this.mSprite = (atlas == null) ? null : atlas.GetSprite(this.spriteName);
         if (this.mSprite != null)
         {
             Texture texture = atlas.texture;
             if (texture == null)
             {
                 this.mSprite = null;
             }
             else
             {
                 this.mUV = new Rect((float) this.mSprite.x, (float) this.mSprite.y, (float) this.mSprite.width, (float) this.mSprite.height);
                 this.mUV = NGUIMath.ConvertToTexCoords(this.mUV, texture.width, texture.height);
                 this.mOffsetX = this.mSprite.paddingLeft;
                 this.mOffsetY = this.mSprite.paddingTop;
                 this.mWidth = this.mSprite.width;
                 this.mHeight = this.mSprite.height;
                 this.mAdvance = this.mSprite.width + (this.mSprite.paddingLeft + this.mSprite.paddingRight);
                 this.mIsValid = true;
             }
         }
     }
     return (this.mSprite != null);
 }
Exemplo n.º 7
0
	static void Load ()
	{
		mLoaded			= true;
		mPartial		= EditorPrefs.GetString("NGUI Partial");
		mFontName		= EditorPrefs.GetString("NGUI Font Name");
		mAtlasName		= EditorPrefs.GetString("NGUI Atlas Name");
		mFontData		= GetObject("NGUI Font Asset") as TextAsset;
		mFontTexture	= GetObject("NGUI Font Texture") as Texture2D;
		mFont			= GetObject("NGUI Font") as UIFont;
		mAtlas			= GetObject("NGUI Atlas") as UIAtlas;
		mAtlasPadding	= EditorPrefs.GetInt("NGUI Atlas Padding", 1);
		mAtlasTrimming	= EditorPrefs.GetBool("NGUI Atlas Trimming", true);
		mAtlasPMA		= EditorPrefs.GetBool("NGUI Atlas PMA", true);
		mUnityPacking	= EditorPrefs.GetBool("NGUI Unity Packing", true);
		mForceSquare	= EditorPrefs.GetBool("NGUI Force Square Atlas", true);
		mPivot			= (UIWidget.Pivot)EditorPrefs.GetInt("NGUI Pivot", (int)mPivot);
		mLayer			= EditorPrefs.GetInt("NGUI Layer", -1);
		mDynFont		= GetObject("NGUI DynFont") as Font;
		mDynFontSize	= EditorPrefs.GetInt("NGUI DynFontSize", 16);
		mDynFontStyle	= (FontStyle)EditorPrefs.GetInt("NGUI DynFontStyle", (int)FontStyle.Normal);

		if (mLayer < 0 || string.IsNullOrEmpty(LayerMask.LayerToName(mLayer))) mLayer = -1;

		if (mLayer == -1) mLayer = LayerMask.NameToLayer("UI");
		if (mLayer == -1) mLayer = LayerMask.NameToLayer("GUI");
		if (mLayer == -1) mLayer = 5;

		EditorPrefs.SetInt("UI Layer", mLayer);

		LoadColor();
	}
Exemplo n.º 8
0
        public AtlasUsages(UIAtlas Atlas)
        {
            this.Atlas = Atlas;
              UsedSprites = new Dictionary<string, SpriteLink>();

              initUnusedSprites();
        }
Exemplo n.º 9
0
    public void initialization()
    {
        itemAtlas = Resources.Load("Atlas/ItemIcon Atlas", typeof(UIAtlas)) as UIAtlas;

        // 임의로한거
         /*   if(itemID == 0)
        {
            itemSpriteName = "Orc Armor - Boots";
        }
        else if(itemID == 1)
        {
            itemSpriteName = "Orc Armor - Bracers";
        }
        else if(itemID == 2)
        {
            itemSpriteName = "Orc Armor - Shoulders";
        }
        else if(itemID == 3)
        {
            itemSpriteName = "NGUI";
        }
        else if(itemID == 4)
        {
            itemSpriteName = "Window";
        }*/
    }
Exemplo n.º 10
0
	/// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	void init()
	{
		atlas_tile = Resources.Load<UIAtlas> (GameCon.basePipeAtlasPath);
		atlas_bgTiles = Resources.Load<UIAtlas> ("Atlases/BackgroundTiles");
		atlas_clockTiles = Resources.Load<UIAtlas> ("Atlases/TopClockTiles");
		atlas_counterTiles = Resources.Load<UIAtlas> ("Atlases/TopCounterTiles");
		atlas_textTiles = Resources.Load<UIAtlas> ("Atlases/TopTextTiles");
	}
Exemplo n.º 11
0
	/// <summary>
	/// Show the selection wizard.
	/// </summary>

	public static void Show (UIAtlas atlas, string selectedSprite, Callback callback)
	{
		SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
		comp.mAtlas = atlas;
		comp.mSprite = null;
		comp.mName = selectedSprite;
		comp.mCallback = callback;
	}
Exemplo n.º 12
0
 /// <summary>
 /// Add a sprite appropriate for the specified atlas sprite.
 /// It will be a UISlicedSprite if the sprite has an inner rect, and a regular sprite otherwise.
 /// </summary>
 public static UISprite Add(GameObject go, UIAtlas atlas, string spriteName)
 {
     UIAtlas.Sprite sp = (atlas != null) ? atlas.GetSprite(spriteName) : null;
     UISprite sprite = (sp == null || sp.inner == sp.outer) ? NGUITools.AddWidget<UISprite>(go) : (UISprite)NGUITools.AddWidget<UISlicedSprite>(go);
     sprite.atlas = atlas;
     sprite.spriteName = spriteName;
     return sprite;
 }
Exemplo n.º 13
0
 void Awake()
 {
     mTrans = transform;
     mSprite = GetComponentInChildren<UISprite>();
     mAtlas = mSprite.atlas;
     mSpriteName = mSprite.spriteName;
     if ( uiCamera == null ) uiCamera = (Singlton.getInstance( "NvCommonUIManager" ) as NvCommonUIManager).SystemUICamera;
 }
Exemplo n.º 14
0
 public static bool CheckIfRelated(UIAtlas a, UIAtlas b)
 {
     if ((a == null) || (b == null))
     {
         return false;
     }
     return (((a == b) || a.References(b)) || b.References(a));
 }
Exemplo n.º 15
0
 /// <summary>
 /// Cache the expected components and starting values.
 /// </summary>
 void Start()
 {
     mTrans = transform;
     mSprite = GetComponentInChildren<UISprite>();
     mAtlas = mSprite.atlas;
     mSpriteName = mSprite.spriteName;
     mSprite.depth = 100;
     if (uiCamera == null) uiCamera = UICamera.mainCamera;//NGUITools.FindCameraForLayer(gameObject.layer);  //Modify By gsl_2013-9-29
 }
	/// <summary>
	/// Cache the expected components and starting values.
	/// </summary>

	void Start ()
	{
		mTrans = transform;
		mSprite = GetComponentInChildren<UISprite>();
		mAtlas = mSprite.atlas;
		mSpriteName = mSprite.spriteName;
		mSprite.depth = 100;
		if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
	}
Exemplo n.º 17
0
	/// <summary>
	/// Override the cursor with the specified sprite.
	/// </summary>

	static public void Set(UIAtlas atlas, string sprite)
	{
		if (instance != null && instance.currentSprite)
		{
			instance.currentSprite.atlas = atlas;
			instance.currentSprite.spriteName = sprite;
			//instance.currentSprite.MakePixelPerfect();
			instance.Update();
		}
	}
Exemplo n.º 18
0
 public static void Set(UIAtlas atlas, string sprite)
 {
     if (UICursor.instance != null && UICursor.instance.mSprite)
     {
         UICursor.instance.mSprite.atlas = atlas;
         UICursor.instance.mSprite.spriteName = sprite;
         UICursor.instance.mSprite.MakePixelPerfect();
         UICursor.instance.Update();
     }
 }
Exemplo n.º 19
0
 public void LoadCharacter()
 {
     string root = "NPCs/Nancy/Minigame/" + topicName + "/";
     _characterTexture = ResourceManager.LoadTexture(root + characterTexture);
     _objectAtlas = ResourceManager.LoadAtlas(root + objectsAtlas);
     Debug.Log("atlas: " + root + objectsAtlas);
     selected = true;
     used = true;
     texture.SetTexture(_characterTexture, Color.white);
 }
Exemplo n.º 20
0
    public void UnloadCharacter()
    {
        Debug.Log (this.gameObject);
        selected = false;
        _characterTexture = null;
        _objectAtlas = null;

        foreach(HiddenObject hiddenObject in hiddenObjects)
            hiddenObject.SetCollider(false);
    }
Exemplo n.º 21
0
 /// <summary>
 /// 鏂板閫夋嫨绮剧伒 淇敼锛氭睙蹇楃ゥ 2013銆?4銆?4
 /// </summary>
 /// <param name="atlas"></param>
 /// <param name="selectedSprite"></param>
 /// <param name="callback"></param>
 public static void Show(UIAtlas atlas, string selectedSprite, SpriteArrayCallback callback, int ArrayID)
 {
     SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
     comp.mAtlas = atlas;
     comp.mSprite = null;
     comp.mName = selectedSprite;
     comp.mCallback = comp.OnSelectSpriteCallBackFuntion;
     comp.mArrayCallBack = callback;
     comp.SpriteID = ArrayID;
 }
Exemplo n.º 22
0
 /// <summary>
 /// Override the cursor with the specified sprite.
 /// </summary>
 public static void Set(UIAtlas atlas, string sprite)
 {
     if (mInstance != null)
     {
         mInstance.mSprite.atlas = atlas;
         mInstance.mSprite.spriteName = sprite;
         mInstance.mSprite.MakePixelPerfect();
         mInstance.Update();
     }
 }
Exemplo n.º 23
0
 /// <summary>
 /// Add the specified texture to the atlas, or update an existing one.
 /// </summary>
 public static void AddOrUpdate(UIAtlas atlas, Texture2D tex)
 {
     if (atlas != null && tex != null)
     {
         List<Texture> textures = new List<Texture>();
         textures.Add(tex);
         List<SpriteEntry> sprites = CreateSprites(textures);
         ExtractSprites(atlas, sprites);
         UpdateAtlas(atlas, sprites);
     }
 }
Exemplo n.º 24
0
    public void Set( UIAtlas atlas, string sprite, object data, int _index )
    {
        mSprite.atlas = atlas;
        mSprite.spriteName = sprite;
        mSprite.MakePixelPerfect();

        userData = data;
        index = _index;

        Update();
    }
Exemplo n.º 25
0
	/// <summary>
	/// Parse the specified JSon file, loading sprite information for the specified atlas.
	/// </summary>

	static public void LoadSpriteData (UIAtlas atlas, string jsonData)
	{
		if (string.IsNullOrEmpty(jsonData) || atlas == null) return;

		Hashtable decodedHash = jsonDecode(jsonData) as Hashtable;

		if (decodedHash == null)
		{
			Debug.LogWarning("Unable to parse the provided Json string");
		}
		else LoadSpriteData(atlas, decodedHash);
	}
Exemplo n.º 26
0
 public void ResetAll()
 {
     coloredTags.Clear();
     allColors.Clear();
     allEffectedObjects.Clear();
     subAtlas = null;
     mainAtlas = null;
     titleFont = null;
     normalFont = null;
     swapTitleFont = null;
     swapNormalFont = null;
 }
Exemplo n.º 27
0
 private void Start()
 {
     this.mTrans = base.transform;
     this.mSprite = base.GetComponentInChildren<UISprite>();
     this.mAtlas = this.mSprite.atlas;
     this.mSpriteName = this.mSprite.spriteName;
     this.mSprite.depth = 100;
     if (this.uiCamera == null)
     {
         this.uiCamera = NGUITools.FindCameraForLayer(base.gameObject.layer);
     }
 }
Exemplo n.º 28
0
    public bool AtlasHaveSprite(UIAtlas atlas, string spriteName)
    {
        bool result = false;

        foreach (UISpriteData spriteData in atlas.spriteList)
        {
            if (spriteData.name == spriteName)
            {
                result = true;
            }
        }
        return result;
    }
Exemplo n.º 29
0
	static void Load ()
	{
		mLoaded			= true;
		mFontName		= EditorPrefs.GetString("NGUI Font Name");
		mAtlasName		= EditorPrefs.GetString("NGUI Atlas Name");
		mFontData		= GetObject("NGUI Font Asset") as TextAsset;
		mFontTexture	= GetObject("NGUI Font Texture") as Texture2D;
		mFont			= GetObject("NGUI Font") as UIFont;
		mAtlas			= GetObject("NGUI Atlas") as UIAtlas;
		mPreview		= EditorPrefs.GetInt("NGUI Preview") == 0;
		mAtlasPadding	= EditorPrefs.GetInt("NGUI Atlas Padding", 1);
		mAtlasTrimming	= EditorPrefs.GetBool("NGUI Atlas Trimming", true);
	}
Exemplo n.º 30
0
	/// <summary>
	/// Replacement atlas selection callback.
	/// </summary>

	void OnSelectAtlas (Object obj)
	{
		if (mReplacement != obj)
		{
			// Undo doesn't work correctly in this case... so I won't bother.
			//NGUIEditorTools.RegisterUndo("Atlas Change");
			//NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

			mAtlas.replacement = obj as UIAtlas;
			mReplacement = mAtlas.replacement;
			NGUITools.SetDirty(mAtlas);
			if (mReplacement == null) mType = AtlasType.Normal;
		}
	}
Exemplo n.º 31
0
 public void setAtlas(UIAtlas atlas)
 {
     mEffectNode.setAtlas(atlas);
 }
Exemplo n.º 32
0
    /// <summary>
    /// 图集引用检测
    /// </summary>
    private void OnAtlasRefGUI()
    {
        //EditorGUILayout.Space();
        string curFolder = EditorGUILayout.TextField("prefab根目录:", _prefabFolder);
        var    curAtlas  = (UIAtlas)EditorGUILayout.ObjectField("UIAtlas:", _targetAtlas, typeof(UIAtlas), false);

        if (curAtlas == null || _targetAtlas != curAtlas || curFolder != _prefabFolder)
        {
            NGUIPrefabAtlasCheck.HitManager.Clear();
            _alreadyCheck = false;
        }

        _targetAtlas  = curAtlas;
        _prefabFolder = curFolder;

        if (GUILayout.Button("Check", "LargeButton", GUILayout.Height(50f)))
        {
            OnCheckAtlas();
            OnCheckIgnore();
            _alreadyCheck = true;
        }

        List <HitManager> hitList    = HitManager.GetAllManagers();
        List <HitManager> notHitList = new List <HitManager>();

        if (hitList.Count > 0)
        {
            GUILayout.BeginHorizontal();
            string after = EditorGUILayout.TextField("", _searchSprite, "SearchTextField");
            if (_searchSprite != after)
            {
                _searchSprite = after;
            }
            GUILayout.EndHorizontal();
            GUILayout.Space(5f);

            _resultScrollPos = EditorGUILayout.BeginScrollView(_resultScrollPos, GUILayout.MinHeight(300f));
            foreach (var manager in hitList)
            {
                if (_searchSprite != null && (!manager.spriteName.Contains(_searchSprite)))
                {
                    continue;
                }

                if (!_spriteFolderExpand.ContainsKey(manager.spriteName))
                {
                    _spriteFolderExpand.Add(manager.spriteName, false);
                }

                if (manager.hitTotal <= 0)
                {
                    GUI.color = Color.red;
                }
                string sFolder = string.Format("{0} Count:{1}", manager.spriteName, manager.hitTotal);
                _spriteFolderExpand[manager.spriteName] = EditorGUILayout.Foldout(_spriteFolderExpand[manager.spriteName], sFolder);
                GUI.color = Color.white;

                if (manager.hitTotal <= 0)
                {
                    notHitList.Add(manager);
                    continue;
                }

                if (_spriteFolderExpand[manager.spriteName])
                {
                    for (int i = 0; i < manager.hitDataList.Count; i++)
                    {
                        HitData data = manager.hitDataList[i];
                        GUILayout.Space(-1f);
                        GUI.backgroundColor = data == _selectHit ? Color.white : new Color(0.8f, 0.8f, 0.8f);
                        GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                        GUI.backgroundColor = Color.white;
                        GUILayout.Space(15f);
                        GUILayout.Label(i.ToString(), GUILayout.Width(40f));
                        string sText = string.Format("{0}.prefab count:{1}", data.prefabName, data.hitCount);
                        if (GUILayout.Button(sText, "OL TextField", GUILayout.Height(20f)))
                        {
                            _selectHit        = data;
                            _selectSpriteName = manager.spriteName;
                        }
                        GUILayout.EndHorizontal();
                    }
                }
            }
            EditorGUILayout.EndScrollView();
            string sResult = string.Format("Search Result: {0}/{1}(未引用/全部)", notHitList.Count, hitList.Count);
            if (EditorHelper.DrawHeader(sResult, "result", false, false))
            {
                _notRefScrollPos = EditorGUILayout.BeginScrollView(_notRefScrollPos, GUILayout.MinHeight(180f));
                foreach (var data in notHitList)
                {
                    GUI.backgroundColor = _ignoreList.Contains(data.spriteName) ? Color.red : Color.white;
                    GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                    GUI.backgroundColor = Color.white;
                    GUILayout.Space(15f);
                    GUILayout.Label(data.spriteName);
                    if (!_ignoreList.Contains(data.spriteName))
                    {
                        if (GUILayout.Button("忽略", GUILayout.Width(60f)))
                        {
                            if (!_ignoreList.Contains(data.spriteName))
                            {
                                _ignoreList.Add(data.spriteName);
                            }
                        }
                    }
                    else
                    {
                        GUI.backgroundColor = Color.green;
                        if (GUILayout.Button("取消忽略", GUILayout.Width(85f)))
                        {
                            if (_ignoreList.Contains(data.spriteName))
                            {
                                _ignoreList.Remove(data.spriteName);
                            }
                        }
                    }
                    GUI.backgroundColor = Color.white;
                    GUILayout.EndHorizontal();
                }
                EditorGUILayout.EndScrollView();
            }


            if (GUILayout.Button("一键移除未被引用的sprite", "LargeButton", GUILayout.Height(50f)))
            {
                if (notHitList.Count > 0)
                {
                    if (EditorUtility.DisplayDialog("确认", "将会删除imgs文件夹下相应的png,确认后请等待数秒", "继续", "取消"))
                    {
                        string atlasPath  = AssetDatabase.GetAssetPath(_targetAtlas);
                        string folderPath = atlasPath.Replace("/" + _targetAtlas.name + ".prefab", "");

                        int total  = 0;
                        int remove = 0;
                        foreach (var manager in notHitList)
                        {
                            ++total;
                            if (_ignoreList.Contains(manager.spriteName))
                            {
                                continue;
                            }
                            string src = folderPath + "/imgs/" + manager.spriteName + ".png";
                            if (AssetDatabase.MoveAssetToTrash(src))
                            {
                                ++remove;
                            }
                        }
                        EditorUtility.DisplayDialog("移除完毕", string.Format("成功移除{0}/{1}。请自行生成新的图集", remove, total), "确定");
                        DoTexturePacker(folderPath, _targetAtlas.name);
                    }
                }
            }

            EditorGUILayout.LabelField("注意:工具只检测prefab是否引用资源,代码引用判断未处理,请人脑判断");
            EditorGUILayout.LabelField("一键移除,在图集目录新建了一个backups文件夹,并把未引用的png资源文件移动进去");
            EditorGUILayout.LabelField("一键移除后,自行使用TexturePacker 工具重新生成");

            if (_selectHit != null)
            {
                string detail = string.Format("{0}图片 {1}.prefab detail:", _selectSpriteName, _selectHit.prefabName);
                if (EditorHelper.DrawHeader(detail, "detail", false, false))
                {
                    _prefabDetailPos = EditorGUILayout.BeginScrollView(_prefabDetailPos, GUILayout.MinHeight(100f));
                    foreach (string path in _selectHit.hitPathList)
                    {
                        GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                        GUILayout.Space(25f);
                        GUILayout.Label(path);
                        GUILayout.EndHorizontal();
                    }
                    EditorGUILayout.EndScrollView();
                }
            }
            else
            {
                EditorHelper.DrawHeader("none select prefab", "detail", false, false);
            }
        }
        else if (_alreadyCheck)//未生成过manager,表示atlas未被引用过
        {
            if (GUILayout.Button("图集未被引用,点击移除", "LargeButton", GUILayout.Height(50f)))
            {
                if (EditorUtility.DisplayDialog("确认", "此操作会移除图集目录,确认继续?", "确认", "取消"))
                {
                    string atlasPath  = AssetDatabase.GetAssetPath(_targetAtlas);
                    string folderPath = atlasPath.Replace("/" + _targetAtlas.name + ".prefab", "");
                    if (AssetDatabase.MoveAssetToTrash(folderPath))
                    {
                        EditorUtility.DisplayDialog("", "移除图集目录成功", "确认");
                    }
                }
            }
        }
    }
Exemplo n.º 33
0
 // Use this for initialization
 void Start()
 {
     _originalAtlas = avatarSprite.atlas;
 }
Exemplo n.º 34
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        EditorGUIUtility.LookLikeControls(80f);
        InvDatabase db = target as InvDatabase;

        NGUIEditorTools.DrawSeparator();

        InvBaseItem item = null;

        if (db.items == null || db.items.Count == 0)
        {
            mIndex = 0;
        }
        else
        {
            mIndex = Mathf.Clamp(mIndex, 0, db.items.Count - 1);
            item   = db.items[mIndex];
        }

        if (mConfirmDelete)
        {
            // Show the confirmation dialog
            GUILayout.Label("Are you sure you want to delete '" + item.name + "'?");
            NGUIEditorTools.DrawSeparator();

            GUILayout.BeginHorizontal();
            {
                GUI.backgroundColor = Color.green;
                if (GUILayout.Button("Cancel"))
                {
                    mConfirmDelete = false;
                }
                GUI.backgroundColor = Color.red;

                if (GUILayout.Button("Delete"))
                {
                    NGUIEditorTools.RegisterUndo("Delete Inventory Item", db);
                    db.items.RemoveAt(mIndex);
                    mConfirmDelete = false;
                }
                GUI.backgroundColor = Color.white;
            }
            GUILayout.EndHorizontal();
        }
        else
        {
            // Database icon atlas
            UIAtlas atlas = EditorGUILayout.ObjectField("Icon Atlas", db.iconAtlas, typeof(UIAtlas), false) as UIAtlas;

            if (atlas != db.iconAtlas)
            {
                NGUIEditorTools.RegisterUndo("Databse Atlas change", db);
                db.iconAtlas = atlas;
                foreach (InvBaseItem i in db.items)
                {
                    i.iconAtlas = atlas;
                }
            }

            // Database ID
            int dbID = EditorGUILayout.IntField("Database ID", db.databaseID);

            if (dbID != db.databaseID)
            {
                NGUIEditorTools.RegisterUndo("Database ID change", db);
                db.databaseID = dbID;
            }

            // "New" button
            GUI.backgroundColor = Color.green;

            if (GUILayout.Button("New Item"))
            {
                NGUIEditorTools.RegisterUndo("Add Inventory Item", db);

                InvBaseItem bi = new InvBaseItem();
                bi.iconAtlas = db.iconAtlas;
                bi.id16      = (db.items.Count > 0) ? db.items[db.items.Count - 1].id16 + 1 : 0;
                db.items.Add(bi);
                mIndex = db.items.Count - 1;

                if (item != null)
                {
                    bi.name         = "Copy of " + item.name;
                    bi.description  = item.description;
                    bi.slot         = item.slot;
                    bi.color        = item.color;
                    bi.iconName     = item.iconName;
                    bi.attachment   = item.attachment;
                    bi.minItemLevel = item.minItemLevel;
                    bi.maxItemLevel = item.maxItemLevel;

                    foreach (InvStat stat in item.stats)
                    {
                        InvStat copy = new InvStat();
                        copy.id       = stat.id;
                        copy.amount   = stat.amount;
                        copy.modifier = stat.modifier;
                        bi.stats.Add(copy);
                    }
                }
                else
                {
                    bi.name        = "New Item";
                    bi.description = "Item Description";
                }

                item = bi;
            }
            GUI.backgroundColor = Color.white;

            if (item != null)
            {
                NGUIEditorTools.DrawSeparator();

                // Navigation section
                GUILayout.BeginHorizontal();
                {
                    if (mIndex == 0)
                    {
                        GUI.color = Color.grey;
                    }
                    if (GUILayout.Button("<<"))
                    {
                        mConfirmDelete = false; --mIndex;
                    }
                    GUI.color = Color.white;
                    mIndex    = EditorGUILayout.IntField(mIndex + 1, GUILayout.Width(40f)) - 1;
                    GUILayout.Label("/ " + db.items.Count, GUILayout.Width(40f));
                    if (mIndex + 1 == db.items.Count)
                    {
                        GUI.color = Color.grey;
                    }
                    if (GUILayout.Button(">>"))
                    {
                        mConfirmDelete = false; ++mIndex;
                    }
                    GUI.color = Color.white;
                }
                GUILayout.EndHorizontal();

                NGUIEditorTools.DrawSeparator();

                // Item name and delete item button
                GUILayout.BeginHorizontal();
                {
                    string itemName = EditorGUILayout.TextField("Item Name", item.name);

                    GUI.backgroundColor = Color.red;

                    if (GUILayout.Button("Delete", GUILayout.Width(55f)))
                    {
                        mConfirmDelete = true;
                    }
                    GUI.backgroundColor = Color.white;

                    if (!itemName.Equals(item.name))
                    {
                        NGUIEditorTools.RegisterUndo("Rename Item", db);
                        item.name = itemName;
                    }
                }
                GUILayout.EndHorizontal();

                string           itemDesc   = GUILayout.TextArea(item.description, 200, GUILayout.Height(100f));
                InvBaseItem.Slot slot       = (InvBaseItem.Slot)EditorGUILayout.EnumPopup("Slot", item.slot);
                string           iconName   = "";
                float            iconSize   = 64f;
                bool             drawIcon   = false;
                float            extraSpace = 0f;

                if (item.iconAtlas != null)
                {
                    List <string> sprites = item.iconAtlas.GetListOfSprites();

                    sprites.Insert(0, "<None>");

                    int    index      = 0;
                    string spriteName = (item.iconName != null) ? item.iconName : sprites[0];

                    // We need to find the sprite in order to have it selected
                    if (!string.IsNullOrEmpty(spriteName))
                    {
                        for (int i = 1; i < sprites.Count; ++i)
                        {
                            if (spriteName.Equals(sprites[i], System.StringComparison.OrdinalIgnoreCase))
                            {
                                index = i;
                                break;
                            }
                        }
                    }

                    // Draw the sprite selection popup
                    index = EditorGUILayout.Popup("Icon", index, sprites.ToArray());
                    UIAtlas.Sprite sprite = (index > 0) ? item.iconAtlas.GetSprite(sprites[index]) : null;

                    if (sprite != null)
                    {
                        iconName = sprite.name;

                        Material mat = item.iconAtlas.spriteMaterial;

                        if (mat != null)
                        {
                            Texture2D tex = mat.mainTexture as Texture2D;

                            if (tex != null)
                            {
                                drawIcon = true;
                                Rect rect = sprite.outer;

                                if (item.iconAtlas.coordinates == UIAtlas.Coordinates.Pixels)
                                {
                                    rect = NGUIMath.ConvertToTexCoords(rect, tex.width, tex.height);
                                }

                                GUILayout.Space(4f);
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.Space(Screen.width - iconSize);
                                    NGUIEditorTools.DrawSprite(tex, rect, null);
                                }
                                GUILayout.EndHorizontal();

                                extraSpace = iconSize * (float)sprite.outer.height / sprite.outer.width;
                            }
                        }
                    }
                }

                // Item level range
                GUILayout.BeginHorizontal();
                GUILayout.Label("Level Range", GUILayout.Width(77f));
                int min = EditorGUILayout.IntField(item.minItemLevel, GUILayout.MinWidth(40f));
                int max = EditorGUILayout.IntField(item.maxItemLevel, GUILayout.MinWidth(40f));
                if (drawIcon)
                {
                    GUILayout.Space(iconSize);
                }
                GUILayout.EndHorizontal();

                // Game Object attachment field, left of the icon
                GUILayout.BeginHorizontal();
                GameObject go = (GameObject)EditorGUILayout.ObjectField("Attachment", item.attachment, typeof(GameObject), false);
                if (drawIcon)
                {
                    GUILayout.Space(iconSize);
                }
                GUILayout.EndHorizontal();

                // Color tint field, left of the icon
                GUILayout.BeginHorizontal();
                Color color = EditorGUILayout.ColorField("Color", item.color);
                if (drawIcon)
                {
                    GUILayout.Space(iconSize);
                }
                GUILayout.EndHorizontal();

                // Calculate the extra spacing necessary for the icon to show up properly and not overlap anything
                if (drawIcon)
                {
                    extraSpace = Mathf.Max(0f, extraSpace - 60f);
                    GUILayout.Space(extraSpace);
                }

                // Item stats
                NGUIEditorTools.DrawSeparator();

                if (item.stats != null)
                {
                    for (int i = 0; i < item.stats.Count; ++i)
                    {
                        InvStat stat = item.stats[i];

                        GUILayout.BeginHorizontal();
                        {
                            InvStat.Identifier iden = (InvStat.Identifier)EditorGUILayout.EnumPopup(stat.id, GUILayout.Width(80f));

                            // Color the field red if it's negative, green if it's positive
                            if (stat.amount > 0)
                            {
                                GUI.backgroundColor = Color.green;
                            }
                            else if (stat.amount < 0)
                            {
                                GUI.backgroundColor = Color.red;
                            }
                            int amount = EditorGUILayout.IntField(stat.amount, GUILayout.Width(40f));
                            GUI.backgroundColor = Color.white;

                            InvStat.Modifier mod = (InvStat.Modifier)EditorGUILayout.EnumPopup(stat.modifier);

                            GUI.backgroundColor = Color.red;
                            if (GUILayout.Button("X", GUILayout.Width(20f)))
                            {
                                NGUIEditorTools.RegisterUndo("Delete Item Stat", db);
                                item.stats.RemoveAt(i);
                                --i;
                            }
                            else if (iden != stat.id || amount != stat.amount || mod != stat.modifier)
                            {
                                NGUIEditorTools.RegisterUndo("Item Stats", db);
                                stat.id       = iden;
                                stat.amount   = amount;
                                stat.modifier = mod;
                            }
                            GUI.backgroundColor = Color.white;
                        }
                        GUILayout.EndHorizontal();
                    }
                }

                if (GUILayout.Button("Add Stat", GUILayout.Width(80f)))
                {
                    NGUIEditorTools.RegisterUndo("Add Item Stat", db);
                    InvStat stat = new InvStat();
                    stat.id = InvStat.Identifier.Armor;
                    item.stats.Add(stat);
                }

                // Save all values
                if (!itemDesc.Equals(item.description) ||
                    slot != item.slot ||
                    go != item.attachment ||
                    color != item.color ||
                    min != item.minItemLevel ||
                    max != item.maxItemLevel ||
                    !iconName.Equals(item.iconName))
                {
                    NGUIEditorTools.RegisterUndo("Item Properties", db);
                    item.description  = itemDesc;
                    item.slot         = slot;
                    item.attachment   = go;
                    item.color        = color;
                    item.iconName     = iconName;
                    item.minItemLevel = min;
                    item.maxItemLevel = max;
                }
            }
        }
    }
Exemplo n.º 35
0
    /// <summary>
    /// 确认转移
    /// </summary>
    /// <param name="hash">要处理文件的hash值</param>
    private void CommitResetSame(string hash)
    {
        if (_areadyDealList.Contains(hash))
        {
            EditorUtility.DisplayDialog("确认", "此条目已处理", "确认");
            return;
        }
        if (_replaceAtlas == null || string.IsNullOrEmpty(_replaceName))
        {
            EditorUtility.DisplayDialog("错误", "请设置好目标图集", "确认");
            return;
        }

        //需要执行的图集
        List <string> compileList = new List <string>();
        //处理移入一个全新图集的情况
        string atlasPath   = AssetDatabase.GetAssetPath(_replaceAtlas);
        bool   inEditAtlas = false;

        foreach (string filename in _hash2Filenames[hash])
        {
            string path = _filename2AtlasPath[filename];
            if (path.Equals(atlasPath))
            {
                inEditAtlas = true;
                break;
            }
        }
        if (!inEditAtlas)
        {
            string srcPng    = _hash2Filenames[hash][0];
            string srcPath   = _filename2AtlasPath[srcPng];
            string srcFolder = srcPath.Substring(0, srcPath.LastIndexOf("/"));

            string destPath   = atlasPath;
            string destFolder = atlasPath.Substring(0, atlasPath.LastIndexOf("/"));
            string destPng    = destFolder + "/imgs/" + _replaceName + ".png";
            if (File.Exists(destPng))
            {
                EditorUtility.DisplayDialog("错误", "目标图集有同名sprite", "确认");
                return;
            }
            AssetDatabase.MoveAsset(srcPng, destPng);
            compileList.Add(destPath);
            Debug.Log(string.Format("移动{0}到{1}", srcPng, destPng));
        }

        List <string> filenames = _hash2Filenames[hash];

        foreach (string filename in filenames)
        {
            //忽略
            if (_ignoreResetList.Contains(filename))
            {
                Debug.Log("忽略检测:" + filename);
                continue;
            }

            HitManager manager = HitManager.GetManager(filename);
            foreach (HitData data in manager.hitDataList)
            {
                GameObject go = AssetDatabase.LoadMainAssetAtPath(data.prefabPath) as GameObject;
                if (go == null)
                {
                    Debug.LogError("找不到prefab:" + data.prefabName);
                    continue;
                }
                foreach (string path in data.hitPathList)
                {
                    var com = go.transform.Find(path);
                    if (com == null)
                    {
                        Debug.LogError(string.Format("{0}找不到对应的SpriteGameObject:{1},请检查",
                                                     go.name, path));
                        continue;
                    }
                    var sprite = com.GetComponent <UISprite>();
                    if (sprite == null)
                    {
                        Debug.LogError(string.Format("{0}找不到对应的Sprite:{1},请检查",
                                                     go.name, path));
                        continue;
                    }
                    sprite.atlas      = _replaceAtlas;
                    sprite.spriteName = _replaceName;
                    EditorUtility.SetDirty(go);
                    //要添加替换log
                    Debug.Log(string.Format("替换了{0}.prefab的{1}", go.name, path));
                }
            }
        }

        //矫正UI.prefab
        string png = "/imgs/" + _replaceName + ".png";

        foreach (string filename in _hash2Filenames[hash])
        {
            if (_ignoreResetList.Contains(filename))
            {
                Debug.Log("忽略移除png:" + filename);
                continue;
            }

            string path = _filename2AtlasPath[filename];
            if (path.Equals(atlasPath))
            {
                Debug.Log("本身不做移除操作" + filename);
                continue;
            }

            AssetDatabase.MoveAssetToTrash(filename);
            Debug.Log("移除png:" + filename);

            if (!compileList.Contains(path))
            {
                compileList.Add(path);
            }
        }

        //执行tps
        foreach (string path in compileList)
        {
            int    index     = path.LastIndexOf("/");
            int    index2    = path.LastIndexOf(".");
            string folder    = path.Substring(0, index);
            string atlasName = path.Substring(index + 1, index2 - index - 1);
            DoTexturePacker(folder, atlasName);
            Debug.Log("执行tps:" + atlasName);
        }

        //转移完毕
        //正式移除检测
        Debug.Log("转移完毕,hash:" + hash);

        _areadyDealList.Add(hash);
        _replaceAtlas = null;
        _replaceName  = null;
        _selFilename  = "";

        EditorUtility.DisplayDialog("转移结束", "转移结束,记得在编辑器Alt+S保存", "确认");
    }
Exemplo n.º 36
0
    //设置升阶信息
    public void SetLiftSkillInfo(PartnerConfig partnerCfg, int stage, int itemId)
    {
        if (partnerCfg == null)
        {
            return;
        }
        List <string> iconList = new List <string>();

        if (iconList == null)
        {
            return;
        }
        iconList.Add(partnerCfg.Icon0);
        iconList.Add(partnerCfg.Icon1);
        iconList.Add(partnerCfg.Icon2);
        iconList.Add(partnerCfg.Icon3);
        List <string> DescList = new List <string>();

        if (DescList == null)
        {
            return;
        }
        DescList.Add(partnerCfg.StageDescription0);
        DescList.Add(partnerCfg.StageDescription1);
        DescList.Add(partnerCfg.StageDescription2);
        DescList.Add(partnerCfg.StageDescription3);
        UIAtlas atlas = null;

        UnityEngine.GameObject goAtlas = CrossObjectHelper.TryCastObject <UnityEngine.GameObject>(ResourceSystem.GetSharedResource(partnerCfg.AtlasPath));
        if (goAtlas != null)
        {
            atlas = goAtlas.GetComponent <UIAtlas>();
        }
        for (int index = 0; index < c_SkillNumMax; ++index)
        {
            if (spLift[index] != null && index < iconList.Count)
            {
                spLift[index].spriteName = iconList[index];
                spLift[index].atlas      = atlas;
            }
            //设置技能图标
            if (lblLifts[index] != null && index < DescList.Count)
            {
                lblLifts[index].text = DescList[index];
            }
            if (stage >= index + 1)
            {
                spLift[index].color = LightColor;
            }
            else
            {
                spLift[index].color = AshColor;
            }

            //设置进阶箭头
            if (index < spArrow.Length && spArrow[index] != null)
            {
                if (stage > index + 1)
                {
                    spArrow[index].spriteName = "sheng-ji-jian-tou1";
                }
                else
                {
                    spArrow[index].spriteName = "sheng-ji-jian-tou2";
                }
            }
            if (stage >= index + 1)
            {
                lblLifts[index].color = SectionColor;
            }
            else
            {
                lblLifts[index].color = AshColor;
            }
        }

        m_PartnerSkillLiftUpItemId = itemId;
        DFMItemIconUtils.Instance.SetItemInfo(ItemIconType.Partner_Skill, goSkillLift, itemId);
        if (stage < 4)
        {
            //if (textureLiftGoods != null) NGUITools.SetActive(textureLiftGoods.gameObject, true);
            if (lblLiftItemNum != null)
            {
                NGUITools.SetActive(lblLiftItemNum.gameObject, true);
            }
            if (btnLiftUp != null)
            {
                NGUITools.SetActive(btnLiftUp.gameObject, true);
            }
            int        itemNeedNum = 0;
            ItemConfig itemCfg     = ItemConfigProvider.Instance.GetDataById(itemId);
            if (itemCfg != null)
            {
                PartnerStageUpConfig stageUpCfg = PartnerStageUpConfigProvider.Instance.GetDataById(stage);
                if (stageUpCfg != null)
                {
                    itemNeedNum = stageUpCfg.ItemCost;
                }
                int ownItemNum = GetItemNum(itemId);
                if (lblLiftItemNum != null)
                {
                    lblLiftItemNum.text = ownItemNum + "/" + itemNeedNum;
                }
                if (itemProgressBar != null && itemNeedNum != 0)
                {
                    itemProgressBar.value = ownItemNum / (float)itemNeedNum;
                }
                bool enable = (ownItemNum >= itemNeedNum);
                EnableButton(btnLiftUp, enable);
            }
        }
        else
        {
            string CHN = StrDictionaryProvider.Instance.GetDictString(359);
            if (lblLiftItemName != null)
            {
                lblLiftItemName.text = CHN;
            }
            if (itemProgressBar != null)
            {
                itemProgressBar.value = 1;
            }
            if (btnLiftUp != null)
            {
                NGUITools.SetActive(btnLiftUp.gameObject, false);
            }
            //if (textureLiftGoods != null) NGUITools.SetActive(textureLiftGoods.gameObject, false);
            if (lblLiftItemNum != null)
            {
                NGUITools.SetActive(lblLiftItemNum.gameObject, false);
            }
        }
    }
Exemplo n.º 37
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);
    }
Exemplo n.º 38
0
    /// <summary>
    /// Combine all sprites into a single texture and save it to disk.
    /// </summary>

    static public bool UpdateTexture(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        // Get the texture for the atlas
        Texture2D tex     = atlas.texture as Texture2D;
        string    oldPath = (tex != null) ? AssetDatabase.GetAssetPath(tex.GetInstanceID()) : "";
        string    newPath = NGUIEditorTools.GetSaveableTexturePath(atlas);

        // Clear the read-only flag in texture file attributes
        if (System.IO.File.Exists(newPath))
        {
#if !UNITY_4_1 && !UNITY_4_0 && !UNITY_3_5
            if (!AssetDatabase.IsOpenForEdit(newPath))
            {
                Debug.LogError(newPath + " is not editable. Did you forget to do a check out?");
                return(false);
            }
#endif
            System.IO.FileAttributes newPathAttrs = System.IO.File.GetAttributes(newPath);
            newPathAttrs &= ~System.IO.FileAttributes.ReadOnly;
            System.IO.File.SetAttributes(newPath, newPathAttrs);
        }

        bool newTexture = (tex == null || oldPath != newPath);

        if (newTexture)
        {
            // Create a new texture for the atlas
            tex = new Texture2D(1, 1, TextureFormat.ARGB32, false);
        }
        else
        {
            // Make the atlas readable so we can save it
            tex = NGUIEditorTools.ImportTexture(oldPath, true, false, false);
        }

        // Pack the sprites into this texture
        if (PackTextures(tex, sprites))
        {
            byte[] bytes = tex.EncodeToPNG();
            System.IO.File.WriteAllBytes(newPath, bytes);
            bytes = null;

            // Load the texture we just saved as a Texture2D
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            tex = NGUIEditorTools.ImportTexture(newPath, false, true, !atlas.premultipliedAlpha);

            // Update the atlas texture
            if (newTexture)
            {
                if (tex == null)
                {
                    Debug.LogError("Failed to load the created atlas saved as " + newPath);
                }
                else
                {
                    atlas.spriteMaterial.mainTexture = tex;
                }
                ReleaseSprites(sprites);

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            }
            return(true);
        }
        else
        {
            if (!newTexture)
            {
                NGUIEditorTools.ImportTexture(oldPath, false, true, !atlas.premultipliedAlpha);
            }

            //Debug.LogError("Operation canceled: The selected sprites can't fit into the atlas.\n" +
            //	"Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead.");

            EditorUtility.DisplayDialog("Operation Canceled", "The selected sprites can't fit into the atlas.\n" +
                                        "Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead", "OK");
            return(false);
        }
    }
Exemplo n.º 39
0
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
        if (mLastAtlas != NGUISettings.atlas)
        {
            mLastAtlas = NGUISettings.atlas;
        }

        bool update  = false;
        bool replace = false;

        NGUIEditorTools.SetLabelWidth(84f);
        GUILayout.Space(3f);

        NGUIEditorTools.DrawHeader("Input", true);
        NGUIEditorTools.BeginContents(false);

        GUILayout.BeginHorizontal();
        {
            ComponentSelector.Draw <UIAtlas>("Atlas", NGUISettings.atlas, OnSelectAtlas, true, GUILayout.MinWidth(80f));

            EditorGUI.BeginDisabledGroup(NGUISettings.atlas == null);
            if (GUILayout.Button("New", GUILayout.Width(40f)))
            {
                NGUISettings.atlas = null;
            }
            EditorGUI.EndDisabledGroup();
        }
        GUILayout.EndHorizontal();

        List <Texture> textures = GetSelectedTextures();

        if (NGUISettings.atlas != null)
        {
            Material mat = NGUISettings.atlas.spriteMaterial;
            Texture  tex = NGUISettings.atlas.texture;

            // Material information
            GUILayout.BeginHorizontal();
            {
                if (mat != null)
                {
                    if (GUILayout.Button("Material", GUILayout.Width(76f)))
                    {
                        Selection.activeObject = mat;
                    }
                    GUILayout.Label(" " + mat.name);
                }
                else
                {
                    GUI.color = Color.grey;
                    GUILayout.Button("Material", GUILayout.Width(76f));
                    GUI.color = Color.white;
                    GUILayout.Label(" N/A");
                }
            }
            GUILayout.EndHorizontal();

            // Texture atlas information
            GUILayout.BeginHorizontal();
            {
                if (tex != null)
                {
                    if (GUILayout.Button("Texture", GUILayout.Width(76f)))
                    {
                        Selection.activeObject = tex;
                    }
                    GUILayout.Label(" " + tex.width + "x" + tex.height);
                }
                else
                {
                    GUI.color = Color.grey;
                    GUILayout.Button("Texture", GUILayout.Width(76f));
                    GUI.color = Color.white;
                    GUILayout.Label(" N/A");
                }
            }
            GUILayout.EndHorizontal();
        }

        GUILayout.BeginHorizontal();
        NGUISettings.atlasPadding = Mathf.Clamp(EditorGUILayout.IntField("Padding", NGUISettings.atlasPadding, GUILayout.Width(100f)), 0, 8);
        GUILayout.Label((NGUISettings.atlasPadding == 1 ? "pixel" : "pixels") + " between sprites");
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.atlasTrimming = EditorGUILayout.Toggle("Trim Alpha", NGUISettings.atlasTrimming, GUILayout.Width(100f));
        GUILayout.Label("Remove empty space");
        GUILayout.EndHorizontal();

        bool fixedShader = false;

        if (NGUISettings.atlas != null)
        {
            Material mat = NGUISettings.atlas.spriteMaterial;

            if (mat != null)
            {
                Shader shader = mat.shader;

                if (shader != null)
                {
                    if (shader.name == "Unlit/Transparent Colored")
                    {
                        NGUISettings.atlasPMA = false;
                        fixedShader           = true;
                    }
                    else if (shader.name == "Unlit/Premultiplied Colored")
                    {
                        NGUISettings.atlasPMA = true;
                        fixedShader           = true;
                    }
                }
            }
        }

        if (!fixedShader)
        {
            GUILayout.BeginHorizontal();
            NGUISettings.atlasPMA = EditorGUILayout.Toggle("PMA Shader", NGUISettings.atlasPMA, GUILayout.Width(100f));
            GUILayout.Label("Pre-multiplied alpha", GUILayout.MinWidth(70f));
            GUILayout.EndHorizontal();
        }

        //GUILayout.BeginHorizontal();
        //NGUISettings.keepPadding = EditorGUILayout.Toggle("Keep Padding", NGUISettings.keepPadding, GUILayout.Width(100f));
        //GUILayout.Label("or replace with trimmed pixels", GUILayout.MinWidth(70f));
        //GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.unityPacking = EditorGUILayout.Toggle("Unity Packer", NGUISettings.unityPacking, GUILayout.Width(100f));
        GUILayout.Label("or custom packer", GUILayout.MinWidth(70f));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.trueColorAtlas = EditorGUILayout.Toggle("Truecolor", NGUISettings.trueColorAtlas, GUILayout.Width(100f));
        GUILayout.Label("force ARGB32 textures", GUILayout.MinWidth(70f));
        GUILayout.EndHorizontal();

        if (!NGUISettings.unityPacking)
        {
            GUILayout.BeginHorizontal();
            NGUISettings.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", NGUISettings.forceSquareAtlas, GUILayout.Width(100f));
            GUILayout.Label("if on, forces a square atlas texture", GUILayout.MinWidth(70f));
            GUILayout.EndHorizontal();
        }

#if UNITY_IPHONE || UNITY_ANDROID
        GUILayout.BeginHorizontal();
        NGUISettings.allow4096 = EditorGUILayout.Toggle("4096x4096", NGUISettings.allow4096, GUILayout.Width(100f));
        GUILayout.Label("if off, limit atlases to 2048x2048");
        GUILayout.EndHorizontal();
#endif
        NGUIEditorTools.EndContents();

        if (NGUISettings.atlas != null)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(20f);

            if (textures.Count > 0)
            {
                update = GUILayout.Button("Add/Update");
            }
            else if (GUILayout.Button("View Sprites"))
            {
                SpriteSelector.ShowSelected();
            }

            GUILayout.Space(20f);
            GUILayout.EndHorizontal();
        }
        else
        {
            EditorGUILayout.HelpBox("You can create a new atlas by selecting one or more textures in the Project View window, then clicking \"Create\".", MessageType.Info);

            EditorGUI.BeginDisabledGroup(textures.Count == 0);
            GUILayout.BeginHorizontal();
            GUILayout.Space(20f);
            bool create = GUILayout.Button("Create");
            GUILayout.Space(20f);
            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            if (create)
            {
                string path = EditorUtility.SaveFilePanelInProject("Save As",
                                                                   "New Atlas.prefab", "prefab", "Save atlas as...", NGUISettings.currentPath);

                if (!string.IsNullOrEmpty(path))
                {
                    NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                    GameObject go      = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
                    string     matPath = path.Replace(".prefab", ".mat");
                    replace = true;

                    // Try to load the material
                    Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                    // If the material doesn't exist, create it
                    if (mat == null)
                    {
                        Shader shader = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                        // Load the material so it's usable
                        mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                    }

                    // Create a new prefab for the atlas
                    Object prefab = (go != null) ? go : PrefabUtility.CreateEmptyPrefab(path);

                    // Create a new game object for the atlas
                    string atlasName = path.Replace(".prefab", "");
                    atlasName = atlasName.Substring(path.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
                    go        = new GameObject(atlasName);
                    go.AddComponent <UIAtlas>().spriteMaterial = mat;

                    // Update the prefab
                    PrefabUtility.ReplacePrefab(go, prefab);
                    DestroyImmediate(go);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                    // Select the atlas
                    go = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
                    NGUISettings.atlas         = go.GetComponent <UIAtlas>();
                    Selection.activeGameObject = go;
                }
            }
        }

        string selection = null;
        Dictionary <string, int> spriteList = GetSpriteList(textures);

        if (spriteList.Count > 0)
        {
            NGUIEditorTools.DrawHeader("Sprites", true);
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(3f);
                GUILayout.BeginVertical();

                mScroll = GUILayout.BeginScrollView(mScroll);

                bool delete = false;
                int  index  = 0;
                foreach (KeyValuePair <string, int> iter in spriteList)
                {
                    ++index;

                    GUILayout.Space(-1f);
                    bool highlight = (UIAtlasInspector.instance != null) && (NGUISettings.selectedSprite == iter.Key);
                    GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
                    GUILayout.BeginHorizontal("TextArea", GUILayout.MinHeight(20f));
                    GUI.backgroundColor = Color.white;
                    GUILayout.Label(index.ToString(), GUILayout.Width(24f));

                    if (GUILayout.Button(iter.Key, "OL TextField", GUILayout.Height(20f)))
                    {
                        selection = iter.Key;
                    }

                    if (iter.Value == 2)
                    {
                        GUI.color = Color.green;
                        GUILayout.Label("Add", GUILayout.Width(27f));
                        GUI.color = Color.white;
                    }
                    else if (iter.Value == 1)
                    {
                        GUI.color = Color.cyan;
                        GUILayout.Label("Update", GUILayout.Width(45f));
                        GUI.color = Color.white;
                    }
                    else
                    {
                        if (mDelNames.Contains(iter.Key))
                        {
                            GUI.backgroundColor = Color.red;

                            if (GUILayout.Button("Delete", GUILayout.Width(60f)))
                            {
                                delete = true;
                            }
                            GUI.backgroundColor = Color.green;
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                mDelNames.Remove(iter.Key);
                                delete = false;
                            }
                            GUI.backgroundColor = Color.white;
                        }
                        else
                        {
                            // If we have not yet selected a sprite for deletion, show a small "X" button
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                mDelNames.Add(iter.Key);
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                GUILayout.EndScrollView();
                GUILayout.EndVertical();
                GUILayout.Space(3f);
                GUILayout.EndHorizontal();

                // If this sprite was marked for deletion, remove it from the atlas
                if (delete)
                {
                    List <SpriteEntry> sprites = new List <SpriteEntry>();
                    ExtractSprites(NGUISettings.atlas, sprites);

                    for (int i = sprites.Count; i > 0;)
                    {
                        SpriteEntry ent = sprites[--i];
                        if (mDelNames.Contains(ent.name))
                        {
                            sprites.RemoveAt(i);
                        }
                    }
                    UpdateAtlas(NGUISettings.atlas, sprites);
                    mDelNames.Clear();
                    NGUIEditorTools.RepaintSprites();
                }
                else if (update)
                {
                    UpdateAtlas(textures, true);
                }
                else if (replace)
                {
                    UpdateAtlas(textures, false);
                }

                if (NGUISettings.atlas != null && !string.IsNullOrEmpty(selection))
                {
                    NGUIEditorTools.SelectSprite(selection);
                }
                else if (update || replace)
                {
                    NGUIEditorTools.UpgradeTexturesToSprites(NGUISettings.atlas);
                    NGUIEditorTools.RepaintSprites();
                }
            }
        }

        if (NGUISettings.atlas != null && textures.Count == 0)
        {
            EditorGUILayout.HelpBox("You can reveal more options by selecting one or more textures in the Project View window.", MessageType.Info);
        }

        // Uncomment this line if you want to be able to force-sort the atlas
        //if (NGUISettings.atlas != null && GUILayout.Button("Sort Alphabetically")) NGUISettings.atlas.SortAlphabetically();
    }
Exemplo n.º 40
0
 public void SetAtlas(UIAtlas atlas)
 {
     mAtlas = atlas;
 }
Exemplo n.º 41
0
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
        if (mLastAtlas != NGUISettings.atlas)
        {
            mLastAtlas = NGUISettings.atlas;
            atlasName  = (NGUISettings.atlas != null) ? NGUISettings.atlas.name : "New Atlas";
        }

        bool create  = false;
        bool update  = false;
        bool replace = false;

        string prefabPath = "";
        string matPath    = "";

        // If we have an atlas to work with, see if we can figure out the path for it and its material
        if (NGUISettings.atlas != null && NGUISettings.atlas.name == atlasName)
        {
            prefabPath = AssetDatabase.GetAssetPath(NGUISettings.atlas.gameObject.GetInstanceID());
            if (NGUISettings.atlas.spriteMaterial != null)
            {
                matPath = AssetDatabase.GetAssetPath(NGUISettings.atlas.spriteMaterial.GetInstanceID());
            }
        }

        // Assume default values if needed
        if (string.IsNullOrEmpty(atlasName))
        {
            atlasName = "New Atlas";
        }
        if (string.IsNullOrEmpty(prefabPath))
        {
            prefabPath = NGUIEditorTools.GetSelectionFolder() + atlasName + ".prefab";
        }
        if (string.IsNullOrEmpty(matPath))
        {
            matPath = NGUIEditorTools.GetSelectionFolder() + atlasName + ".mat";
        }

        // Try to load the prefab
        GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;

        if (NGUISettings.atlas == null && go != null)
        {
            NGUISettings.atlas = go.GetComponent <UIAtlas>();
        }

        NGUIEditorTools.SetLabelWidth(80f);

        GUILayout.Space(6f);
        GUILayout.BeginHorizontal();

        if (go == null)
        {
            GUI.backgroundColor = Color.green;
            create = GUILayout.Button("Create", GUILayout.Width(76f));
        }
        else
        {
            GUI.backgroundColor = Color.red;
            create = GUILayout.Button("Replace", GUILayout.Width(76f));
        }

        GUI.backgroundColor = Color.white;
        atlasName           = GUILayout.TextField(atlasName);
        GUILayout.EndHorizontal();

        if (create)
        {
            // If the prefab already exists, confirm that we want to overwrite it
            if (go == null || EditorUtility.DisplayDialog("Are you sure?", "Are you sure you want to replace the contents of the " +
                                                          atlasName + " atlas with the textures currently selected in the Project View? All other sprites will be deleted.", "Yes", "No"))
            {
                replace = true;

                // Try to load the material
                Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                // If the material doesn't exist, create it
                if (mat == null)
                {
                    Shader shader = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
                    mat = new Material(shader);

                    // Save the material
                    AssetDatabase.CreateAsset(mat, matPath);
                    AssetDatabase.Refresh();

                    // Load the material so it's usable
                    mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                }

                if (NGUISettings.atlas == null || NGUISettings.atlas.name != atlasName)
                {
                    // Create a new prefab for the atlas
                    Object prefab = (go != null) ? go : PrefabUtility.CreateEmptyPrefab(prefabPath);

                    // Create a new game object for the atlas
                    go = new GameObject(atlasName);
                    go.AddComponent <UIAtlas>().spriteMaterial = mat;

                    // Update the prefab
                    PrefabUtility.ReplacePrefab(go, prefab);
                    DestroyImmediate(go);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();

                    // Select the atlas
                    go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
                    NGUISettings.atlas = go.GetComponent <UIAtlas>();
                }
            }
        }

        ComponentSelector.Draw <UIAtlas>("Select", NGUISettings.atlas, OnSelectAtlas, true);

        List <Texture> textures = GetSelectedTextures();

        if (NGUISettings.atlas != null && NGUISettings.atlas.name == atlasName)
        {
            Material mat = NGUISettings.atlas.spriteMaterial;
            Texture  tex = NGUISettings.atlas.texture;

            // Material information
            GUILayout.BeginHorizontal();
            {
                if (mat != null)
                {
                    if (GUILayout.Button("Material", GUILayout.Width(76f)))
                    {
                        Selection.activeObject = mat;
                    }
                    GUILayout.Label(" " + mat.name);
                }
                else
                {
                    GUI.color = Color.grey;
                    GUILayout.Button("Material", GUILayout.Width(76f));
                    GUI.color = Color.white;
                    GUILayout.Label(" N/A");
                }
            }
            GUILayout.EndHorizontal();

            // Texture atlas information
            GUILayout.BeginHorizontal();
            {
                if (tex != null)
                {
                    if (GUILayout.Button("Texture", GUILayout.Width(76f)))
                    {
                        Selection.activeObject = tex;
                    }
                    GUILayout.Label(" " + tex.width + "x" + tex.height);
                }
                else
                {
                    GUI.color = Color.grey;
                    GUILayout.Button("Texture", GUILayout.Width(76f));
                    GUI.color = Color.white;
                    GUILayout.Label(" N/A");
                }
            }
            GUILayout.EndHorizontal();
        }

        GUILayout.BeginHorizontal();
        NGUISettings.atlasPadding = Mathf.Clamp(EditorGUILayout.IntField("Padding", NGUISettings.atlasPadding, GUILayout.Width(100f)), 0, 8);
        GUILayout.Label((NGUISettings.atlasPadding == 1 ? "pixel" : "pixels") + " in-between of sprites");
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.atlasTrimming = EditorGUILayout.Toggle("Trim Alpha", NGUISettings.atlasTrimming, GUILayout.Width(100f));
        GUILayout.Label("Remove empty space");
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.atlasPMA = EditorGUILayout.Toggle("PMA Shader", NGUISettings.atlasPMA, GUILayout.Width(100f));
        GUILayout.Label("Pre-multiply color by alpha");
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        NGUISettings.unityPacking = EditorGUILayout.Toggle("Unity Packer", NGUISettings.unityPacking, GUILayout.Width(100f));
        GUILayout.Label("if off, use a custom packer");
        GUILayout.EndHorizontal();

        if (!NGUISettings.unityPacking)
        {
            GUILayout.BeginHorizontal();
            NGUISettings.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", NGUISettings.forceSquareAtlas, GUILayout.Width(100f));
            GUILayout.Label("if on, forces a square atlas texture");
            GUILayout.EndHorizontal();
        }

#if UNITY_IPHONE || UNITY_ANDROID
        GUILayout.BeginHorizontal();
        NGUISettings.allow4096 = EditorGUILayout.Toggle("4096x4096", NGUISettings.allow4096, GUILayout.Width(100f));
        GUILayout.Label("if off, limit atlases to 2048x2048");
        GUILayout.EndHorizontal();
#endif
        if (NGUISettings.atlas != null && NGUISettings.atlas.name == atlasName)
        {
            if (textures.Count > 0)
            {
                GUI.backgroundColor = Color.green;
                update = GUILayout.Button("Add/Update All");
                GUI.backgroundColor = Color.white;
            }
            else
            {
                if (GUILayout.Button("View Sprites"))
                {
                    SpriteSelector.ShowSelected();
                }
                EditorGUILayout.HelpBox("You can reveal more options by selecting one or more textures in the Project View window.", MessageType.Info);
            }
        }
        else
        {
            EditorGUILayout.HelpBox("You can create a new atlas by selecting one or more textures in the Project View window, then clicking \"Create\".", MessageType.Info);
        }

        string selection = null;
        Dictionary <string, int> spriteList = GetSpriteList(textures);

        if (spriteList.Count > 0)
        {
            NGUIEditorTools.DrawHeader("Sprites", true);
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(3f);
                GUILayout.BeginVertical();

                mScroll = GUILayout.BeginScrollView(mScroll);

                bool delete = false;
                int  index  = 0;
                foreach (KeyValuePair <string, int> iter in spriteList)
                {
                    ++index;

                    GUILayout.Space(-1f);
                    bool highlight = (UIAtlasInspector.instance != null) && (NGUISettings.selectedSprite == iter.Key);
                    GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
                    GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                    GUI.backgroundColor = Color.white;
                    GUILayout.Label(index.ToString(), GUILayout.Width(24f));

                    if (GUILayout.Button(iter.Key, "OL TextField", GUILayout.Height(20f)))
                    {
                        selection = iter.Key;
                    }

                    if (iter.Value == 2)
                    {
                        GUI.color = Color.green;
                        GUILayout.Label("Add", GUILayout.Width(27f));
                        GUI.color = Color.white;
                    }
                    else if (iter.Value == 1)
                    {
                        GUI.color = Color.cyan;
                        GUILayout.Label("Update", GUILayout.Width(45f));
                        GUI.color = Color.white;
                    }
                    else
                    {
                        if (mDelNames.Contains(iter.Key))
                        {
                            GUI.backgroundColor = Color.red;

                            if (GUILayout.Button("Delete", GUILayout.Width(60f)))
                            {
                                delete = true;
                            }
                            GUI.backgroundColor = Color.green;
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                mDelNames.Remove(iter.Key);
                                delete = false;
                            }
                            GUI.backgroundColor = Color.white;
                        }
                        else
                        {
                            // If we have not yet selected a sprite for deletion, show a small "X" button
                            if (GUILayout.Button("X", GUILayout.Width(22f)))
                            {
                                mDelNames.Add(iter.Key);
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                GUILayout.EndScrollView();
                GUILayout.EndVertical();
                GUILayout.Space(3f);
                GUILayout.EndHorizontal();

                // If this sprite was marked for deletion, remove it from the atlas
                if (delete)
                {
                    List <SpriteEntry> sprites = new List <SpriteEntry>();
                    ExtractSprites(NGUISettings.atlas, sprites);

                    for (int i = sprites.Count; i > 0;)
                    {
                        SpriteEntry ent = sprites[--i];
                        if (mDelNames.Contains(ent.name))
                        {
                            sprites.RemoveAt(i);
                        }
                    }
                    UpdateAtlas(NGUISettings.atlas, sprites);
                    mDelNames.Clear();
                    NGUIEditorTools.RepaintSprites();
                }
                else if (update)
                {
                    UpdateAtlas(textures, true);
                }
                else if (replace)
                {
                    UpdateAtlas(textures, false);
                }

                if (NGUISettings.atlas != null && !string.IsNullOrEmpty(selection))
                {
                    NGUIEditorTools.SelectSprite(selection);
                }
                else if (update || replace)
                {
                    NGUIEditorTools.UpgradeTexturesToSprites(NGUISettings.atlas);
                    NGUIEditorTools.RepaintSprites();
                }
            }
        }

        // Uncomment this line if you want to be able to force-sort the atlas
        //if (NGUISettings.atlas != null && GUILayout.Button("Sort Alphabetically")) NGUISettings.atlas.SortAlphabetically();
    }
Exemplo n.º 42
0
    void OnGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);

        if (NGUISettings.atlas == null)
        {
            GUILayout.Label("No Atlas selected.", "LODLevelNotifyText");
        }
        else
        {
            UIAtlas atlas = NGUISettings.atlas;
            bool    close = false;
            GUILayout.Label(atlas.name + " Sprites", "LODLevelNotifyText");
            NGUIEditorTools.DrawSeparator();

            Rect lastRect       = GUILayoutUtility.GetLastRect();
            Rect spriteListRect = new Rect(lastRect.width / 2, lastRect.y, lastRect.width / 2, lastRect.height);

            //GUILayout.BeginArea(lastRect);
            GUILayout.BeginHorizontal();
            GUILayout.Space(84f);

            string before = NGUISettings.partialSprite;
            string after  = EditorGUILayout.TextField("", before, "SearchTextField");
            if (before != after)
            {
                NGUISettings.partialSprite = after;
            }

            if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(18f)))
            {
                NGUISettings.partialSprite = "";
                GUIUtility.keyboardControl = 0;
            }
            GUILayout.Space(84f);
            GUILayout.EndHorizontal();

            Texture2D tex = atlas.texture as Texture2D;

            if (tex == null)
            {
                GUILayout.Label("The atlas doesn't have a texture to work with");
                return;
            }

            BetterList <string> sprites = atlas.GetListOfSprites(NGUISettings.partialSprite);

            float size   = 80f;
            float padded = size + 10f;
#if UNITY_4_7
            int screenWidth = Screen.width;
#else
            int screenWidth = (int)EditorGUIUtility.currentViewWidth;
#endif
            int columns = Mathf.FloorToInt(screenWidth / padded);
            if (columns < 1)
            {
                columns = 1;
            }

            int  offset = 0;
            Rect rect   = new Rect(10f, 0, size, size);

            GUILayout.Space(10f);
            mPos = GUILayout.BeginScrollView(mPos);
            int rows = 1;

            while (offset < sprites.size)
            {
                GUILayout.BeginHorizontal();
                {
                    int col = 0;
                    rect.x = 10f;

                    for (; offset < sprites.size; ++offset)
                    {
                        UISpriteData sprite = atlas.GetSprite(sprites[offset]);
                        if (sprite == null)
                        {
                            continue;
                        }

                        // Button comes first
                        if (GUI.Button(rect, ""))
                        {
                            if (Event.current.button == 0)
                            {
                                float delta = Time.realtimeSinceStartup - mClickTime;
                                mClickTime = Time.realtimeSinceStartup;

                                if (NGUISettings.selectedSprite != sprite.name)
                                {
                                    if (mSprite != null)
                                    {
                                        NGUIEditorTools.RegisterUndo("Atlas Selection", mSprite);
                                        mSprite.MakePixelPerfect();
                                        EditorUtility.SetDirty(mSprite.gameObject);
                                    }

                                    NGUISettings.selectedSprite = sprite.name;
                                    NGUIEditorTools.RepaintSprites();
                                    if (mCallback != null)
                                    {
                                        mCallback(sprite.name);
                                    }
                                }
                                else if (delta < 0.5f)
                                {
                                    close = true;
                                }
                            }
                            else
                            {
                                NGUIContextMenu.AddItem("Edit", false, EditSprite, sprite);
                                NGUIContextMenu.AddItem("Delete", false, DeleteSprite, sprite);
                                NGUIContextMenu.Show();
                            }
                        }

                        if (Event.current.type == EventType.Repaint)
                        {
                            // On top of the button we have a checkboard grid
                            NGUIEditorTools.DrawTiledTexture(rect, NGUIEditorTools.backdropTexture);
                            Rect uv = new Rect(sprite.x, sprite.y, sprite.width, sprite.height);
                            uv = NGUIMath.ConvertToTexCoords(uv, tex.width, tex.height);

                            // Calculate the texture's scale that's needed to display the sprite in the clipped area
                            float scaleX = rect.width / uv.width;
                            float scaleY = rect.height / uv.height;

                            // Stretch the sprite so that it will appear proper
                            float aspect   = (scaleY / scaleX) / ((float)tex.height / tex.width);
                            Rect  clipRect = rect;

                            if (aspect != 1f)
                            {
                                if (aspect < 1f)
                                {
                                    // The sprite is taller than it is wider
                                    float padding = size * (1f - aspect) * 0.5f;
                                    clipRect.xMin += padding;
                                    clipRect.xMax -= padding;
                                }
                                else
                                {
                                    // The sprite is wider than it is taller
                                    float padding = size * (1f - 1f / aspect) * 0.5f;
                                    clipRect.yMin += padding;
                                    clipRect.yMax -= padding;
                                }
                            }

                            GUI.DrawTextureWithTexCoords(clipRect, tex, uv);

                            // Draw the selection
                            if (NGUISettings.selectedSprite == sprite.name)
                            {
                                NGUIEditorTools.DrawOutline(rect, new Color(0.4f, 1f, 0f, 1f));
                            }
                        }

                        GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f);
                        GUI.contentColor    = new Color(1f, 1f, 1f, 0.7f);
                        GUI.Label(new Rect(rect.x, rect.y + rect.height, rect.width, 32f), sprite.name, "ProgressBarBack");
                        GUI.contentColor    = Color.white;
                        GUI.backgroundColor = Color.white;

                        if (++col >= columns)
                        {
                            ++offset;
                            break;
                        }
                        rect.x += padded;
                    }
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(padded);
                rect.y += padded + 26;
                ++rows;
            }
            GUILayout.Space(rows * 26);
            GUILayout.EndScrollView();

            //GUILayout.EndArea();
            if (close)
            {
                Close();
            }
        }
    }
Exemplo n.º 43
0
    /// <summary>
    /// 指定した桁数の数字を画面に表示する
    /// </summary>
    /// <param name="_iNum">表示したい数</param>
    /// <param name="_strHead">画像名</param>
    /// <param name="_iKeta">最大表示桁数</param>
    /// <param name="_bFill">0詰めにするかどうか<c>true</c> _b fill.</param>
    /// <param name="_fWidth">横幅</param>
    /// <param name="_fHeight">縦幅</param>
    /// <param name="_fOffset">数字同士の間隔(オフセット量)</param>
    /// <param name="_fInterval">カウントアップしていく間隔</param>
    public void Initialize(int _iNum, string _strHead, int _iKeta, bool _bFill, float _fWidth, float _fHeight, float _fOffset, float _fInterval, UIAtlas _atlNumber = null)
    {
        foreach (GameObject obj in m_ObjList)
        {
            Release(obj);
        }
        m_ObjList.Clear();

        m_iNumDisp   = _iNum;
        m_iNum       = _iNum;
        m_iNumTarget = _iNum;
        m_strHead    = _strHead;

        m_fTimer    = 0.0f;
        m_iKeta     = _iKeta;
        m_bFill     = _bFill;
        m_fWidth    = _fWidth;
        m_fHeight   = _fHeight;
        m_fOffset   = _fOffset;
        m_fInterval = _fInterval;

        if (_atlNumber == null)
        {
            _atlNumber = GetComponent <UIAtlas> ();
        }
        m_atlNumber = _atlNumber;

        m_arrDispNumber = new CtrlDispNumber[m_iKeta];

        for (int i = 0; i < m_iKeta; i++)
        {
            GameObject obj = AddChildGameObject("keta" + i.ToString());
            obj.transform.localPosition = new Vector3(m_fpos + (m_fWidth + m_fOffset) * i * -1, 0.0f, 0.0f);
            m_arrDispNumber [i]         = obj.AddComponent <CtrlDispNumber> ();
            m_arrDispNumber [i].Initialize(m_strHead, m_atlNumber, m_fWidth, m_fHeight);
            //m_arrDispNumber [i].Initialize (m_strHead , m_atlNumber, 100.0f, 200.0f);
            m_ObjList.Add(obj);
        }
        SetNum(m_iNumTarget);
        m_eStep = STEP.IDLE;

        return;
    }
Exemplo n.º 44
0
    /// <summary>
    /// Draw a sprite selection field.
    /// </summary>

    static public void SpriteField(string fieldName, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback)
    {
        SpriteField(fieldName, null, atlas, spriteName, callback);
    }
Exemplo n.º 45
0
    public unsafe override void Unity_NamedDeserialize(int depth)
    {
        byte[] var_0_cp_0;
        int    var_0_cp_1;

        if (depth <= 7)
        {
            if (this.leftAnchor == null)
            {
                this.leftAnchor = new UIRect.AnchorPoint();
            }
            UIRect.AnchorPoint          arg_3F_0 = this.leftAnchor;
            ISerializedNamedStateReader arg_37_0 = SerializedNamedStateReader.Instance;
            var_0_cp_0 = $FieldNamesStorage.$RuntimeNames;
            var_0_cp_1 = 0;
            arg_37_0.BeginMetaGroup(&var_0_cp_0[var_0_cp_1] + 2296);
            arg_3F_0.Unity_NamedDeserialize(depth + 1);
            SerializedNamedStateReader.Instance.EndMetaGroup();
        }
        if (depth <= 7)
        {
            if (this.rightAnchor == null)
            {
                this.rightAnchor = new UIRect.AnchorPoint();
            }
            UIRect.AnchorPoint arg_82_0 = this.rightAnchor;
            SerializedNamedStateReader.Instance.BeginMetaGroup(&var_0_cp_0[var_0_cp_1] + 2307);
            arg_82_0.Unity_NamedDeserialize(depth + 1);
            SerializedNamedStateReader.Instance.EndMetaGroup();
        }
        if (depth <= 7)
        {
            if (this.bottomAnchor == null)
            {
                this.bottomAnchor = new UIRect.AnchorPoint();
            }
            UIRect.AnchorPoint arg_C5_0 = this.bottomAnchor;
            SerializedNamedStateReader.Instance.BeginMetaGroup(&var_0_cp_0[var_0_cp_1] + 2319);
            arg_C5_0.Unity_NamedDeserialize(depth + 1);
            SerializedNamedStateReader.Instance.EndMetaGroup();
        }
        if (depth <= 7)
        {
            if (this.topAnchor == null)
            {
                this.topAnchor = new UIRect.AnchorPoint();
            }
            UIRect.AnchorPoint arg_108_0 = this.topAnchor;
            SerializedNamedStateReader.Instance.BeginMetaGroup(&var_0_cp_0[var_0_cp_1] + 2332);
            arg_108_0.Unity_NamedDeserialize(depth + 1);
            SerializedNamedStateReader.Instance.EndMetaGroup();
        }
        this.updateAnchors = (UIRect.AnchorUpdate)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 741);
        if (depth <= 7)
        {
            SerializedNamedStateReader.Instance.BeginMetaGroup(&var_0_cp_0[var_0_cp_1] + 2342);
            this.mColor.Unity_NamedDeserialize(depth + 1);
            SerializedNamedStateReader.Instance.EndMetaGroup();
        }
        SerializedNamedStateReader.Instance.Align();
        this.mPivot  = (UIWidget.Pivot)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2349);
        this.mWidth  = SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2098);
        this.mHeight = SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2105);
        this.mDepth  = SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2356);
        this.autoResizeBoxCollider = SerializedNamedStateReader.Instance.ReadBoolean(&var_0_cp_0[var_0_cp_1] + 2363);
        SerializedNamedStateReader.Instance.Align();
        this.hideIfOffScreen = SerializedNamedStateReader.Instance.ReadBoolean(&var_0_cp_0[var_0_cp_1] + 2385);
        SerializedNamedStateReader.Instance.Align();
        this.skipBoundsCalculations = SerializedNamedStateReader.Instance.ReadBoolean(&var_0_cp_0[var_0_cp_1] + 2401);
        SerializedNamedStateReader.Instance.Align();
        this.keepAspectRatio = (UIWidget.AspectRatioSource)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2424);
        this.aspectRatio     = SerializedNamedStateReader.Instance.ReadSingle(&var_0_cp_0[var_0_cp_1] + 2440);
        this.mType           = (UIBasicSprite.Type)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2452);
        this.mFillDirection  = (UIBasicSprite.FillDirection)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2458);
        this.mFillAmount     = SerializedNamedStateReader.Instance.ReadSingle(&var_0_cp_0[var_0_cp_1] + 2473);
        this.mInvert         = SerializedNamedStateReader.Instance.ReadBoolean(&var_0_cp_0[var_0_cp_1] + 2485);
        SerializedNamedStateReader.Instance.Align();
        this.mFlip      = (UIBasicSprite.Flip)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2493);
        this.centerType = (UIBasicSprite.AdvancedType)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2499);
        this.leftType   = (UIBasicSprite.AdvancedType)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2510);
        this.rightType  = (UIBasicSprite.AdvancedType)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2519);
        this.bottomType = (UIBasicSprite.AdvancedType)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2529);
        this.topType    = (UIBasicSprite.AdvancedType)SerializedNamedStateReader.Instance.ReadInt32(&var_0_cp_0[var_0_cp_1] + 2540);
        if (depth <= 7)
        {
            this.mAtlas = (SerializedNamedStateReader.Instance.ReadUnityEngineObject(&var_0_cp_0[var_0_cp_1] + 3531) as UIAtlas);
        }
        this.mSpriteName = (SerializedNamedStateReader.Instance.ReadString(&var_0_cp_0[var_0_cp_1] + 2113) as string);
        this.mFillCenter = SerializedNamedStateReader.Instance.ReadBoolean(&var_0_cp_0[var_0_cp_1] + 4429);
        SerializedNamedStateReader.Instance.Align();
    }
Exemplo n.º 46
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
            }
        }

        if (EventDelegate.IsValid(onChange))
        {
            EventDelegate.Execute(onChange);
        }
    }
Exemplo n.º 47
0
 public override void Unity_Deserialize(int depth)
 {
     if (depth <= 7)
     {
         if (this.leftAnchor == null)
         {
             this.leftAnchor = new UIRect.AnchorPoint();
         }
         this.leftAnchor.Unity_Deserialize(depth + 1);
     }
     if (depth <= 7)
     {
         if (this.rightAnchor == null)
         {
             this.rightAnchor = new UIRect.AnchorPoint();
         }
         this.rightAnchor.Unity_Deserialize(depth + 1);
     }
     if (depth <= 7)
     {
         if (this.bottomAnchor == null)
         {
             this.bottomAnchor = new UIRect.AnchorPoint();
         }
         this.bottomAnchor.Unity_Deserialize(depth + 1);
     }
     if (depth <= 7)
     {
         if (this.topAnchor == null)
         {
             this.topAnchor = new UIRect.AnchorPoint();
         }
         this.topAnchor.Unity_Deserialize(depth + 1);
     }
     this.updateAnchors = (UIRect.AnchorUpdate)SerializedStateReader.Instance.ReadInt32();
     if (depth <= 7)
     {
         this.mColor.Unity_Deserialize(depth + 1);
     }
     SerializedStateReader.Instance.Align();
     this.mPivot  = (UIWidget.Pivot)SerializedStateReader.Instance.ReadInt32();
     this.mWidth  = SerializedStateReader.Instance.ReadInt32();
     this.mHeight = SerializedStateReader.Instance.ReadInt32();
     this.mDepth  = SerializedStateReader.Instance.ReadInt32();
     this.autoResizeBoxCollider = SerializedStateReader.Instance.ReadBoolean();
     SerializedStateReader.Instance.Align();
     this.hideIfOffScreen = SerializedStateReader.Instance.ReadBoolean();
     SerializedStateReader.Instance.Align();
     this.skipBoundsCalculations = SerializedStateReader.Instance.ReadBoolean();
     SerializedStateReader.Instance.Align();
     this.keepAspectRatio = (UIWidget.AspectRatioSource)SerializedStateReader.Instance.ReadInt32();
     this.aspectRatio     = SerializedStateReader.Instance.ReadSingle();
     this.mType           = (UIBasicSprite.Type)SerializedStateReader.Instance.ReadInt32();
     this.mFillDirection  = (UIBasicSprite.FillDirection)SerializedStateReader.Instance.ReadInt32();
     this.mFillAmount     = SerializedStateReader.Instance.ReadSingle();
     this.mInvert         = SerializedStateReader.Instance.ReadBoolean();
     SerializedStateReader.Instance.Align();
     this.mFlip      = (UIBasicSprite.Flip)SerializedStateReader.Instance.ReadInt32();
     this.centerType = (UIBasicSprite.AdvancedType)SerializedStateReader.Instance.ReadInt32();
     this.leftType   = (UIBasicSprite.AdvancedType)SerializedStateReader.Instance.ReadInt32();
     this.rightType  = (UIBasicSprite.AdvancedType)SerializedStateReader.Instance.ReadInt32();
     this.bottomType = (UIBasicSprite.AdvancedType)SerializedStateReader.Instance.ReadInt32();
     this.topType    = (UIBasicSprite.AdvancedType)SerializedStateReader.Instance.ReadInt32();
     if (depth <= 7)
     {
         this.mAtlas = (SerializedStateReader.Instance.ReadUnityEngineObject() as UIAtlas);
     }
     this.mSpriteName = (SerializedStateReader.Instance.ReadString() as string);
     this.mFillCenter = SerializedStateReader.Instance.ReadBoolean();
     SerializedStateReader.Instance.Align();
 }
Exemplo n.º 48
0
 private void OnDisable()
 {
     this.m_uiAtlas = null;
 }
Exemplo n.º 49
0
    /// <summary>
    /// Draw the label's properties.
    /// </summary>

    protected override bool ShouldDrawProperties()
    {
        mLabel = mWidget as UISymbolLabel;

        GUILayout.BeginHorizontal();

#if DYNAMIC_FONT
        mFontType = (FontType)EditorGUILayout.EnumPopup(mFontType, "DropDown", GUILayout.Width(74f));
        if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(64f)))
#else
        mFontType = FontType.NGUI;
        if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(74f)))
#endif
        {
            if (mFontType == FontType.NGUI)
            {
                ComponentSelector.Show <UIFont>(OnNGUIFont);
            }
            else
            {
                ComponentSelector.Show <Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
            }
        }

        bool isValid           = false;
        SerializedProperty fnt = null;
        SerializedProperty ttf = null;

        if (mFontType == FontType.NGUI)
        {
            GUI.changed = false;
            fnt         = NGUIEditorTools.DrawProperty("", serializedObject, "mFont", GUILayout.MinWidth(40f));

            if (fnt.objectReferenceValue != null)
            {
                if (GUI.changed)
                {
                    serializedObject.FindProperty("mTrueTypeFont").objectReferenceValue = null;
                }
                NGUISettings.ambigiousFont = fnt.objectReferenceValue;
                isValid = true;
            }
        }
        else
        {
            GUI.changed = false;
            ttf         = NGUIEditorTools.DrawProperty("", serializedObject, "mTrueTypeFont", GUILayout.MinWidth(40f));

            if (ttf.objectReferenceValue != null)
            {
                if (GUI.changed)
                {
                    serializedObject.FindProperty("mFont").objectReferenceValue = null;
                }
                NGUISettings.ambigiousFont = ttf.objectReferenceValue;
                isValid = true;
            }
        }

        GUILayout.EndHorizontal();

        if (mFontType == FontType.Unity)
        {
            EditorGUILayout.HelpBox("Dynamic fonts suffer from issues in Unity itself where your characters may disappear, get garbled, or just not show at times. Use this feature at your own risk.\n\n" +
                                    "When you do run into such issues, please submit a Bug Report to Unity via Help -> Report a Bug (as this is will be a Unity bug, not an NGUI one).", MessageType.Warning);
        }

        EditorGUI.BeginDisabledGroup(!isValid);
        {
            UIFont uiFont  = (fnt != null) ? fnt.objectReferenceValue as UIFont : null;
            Font   dynFont = (ttf != null) ? ttf.objectReferenceValue as Font : null;

            if (uiFont != null && uiFont.isDynamic)
            {
                dynFont = uiFont.dynamicFont;
                uiFont  = null;
            }

            if (dynFont != null)
            {
                GUILayout.BeginHorizontal();
                {
                    EditorGUI.BeginDisabledGroup((ttf != null) ? ttf.hasMultipleDifferentValues : fnt.hasMultipleDifferentValues);

                    SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));
                    NGUISettings.fontSize = prop.intValue;

                    prop = NGUIEditorTools.DrawProperty("", serializedObject, "mFontStyle", GUILayout.MinWidth(40f));
                    NGUISettings.fontStyle = (FontStyle)prop.intValue;

                    NGUIEditorTools.DrawPadding();
                    EditorGUI.EndDisabledGroup();
                }
                GUILayout.EndHorizontal();

                NGUIEditorTools.DrawProperty("Material", serializedObject, "mMaterial");
            }
            else if (uiFont != null)
            {
                GUILayout.BeginHorizontal();
                SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));

                EditorGUI.BeginDisabledGroup(true);
                if (!serializedObject.isEditingMultipleObjects)
                {
                    if (mLabel.overflowMethod == UISymbolLabel.Overflow.ShrinkContent)
                    {
                        GUILayout.Label(" Actual: " + mLabel.finalFontSize + "/" + mLabel.defaultFontSize);
                    }
                    else
                    {
                        GUILayout.Label(" Default: " + mLabel.defaultFontSize);
                    }
                }
                EditorGUI.EndDisabledGroup();

                NGUISettings.fontSize = prop.intValue;
                GUILayout.EndHorizontal();
            }

            bool ww = GUI.skin.textField.wordWrap;
            GUI.skin.textField.wordWrap = true;
            SerializedProperty sp = serializedObject.FindProperty("mText");

            if (sp.hasMultipleDifferentValues)
            {
                NGUIEditorTools.DrawProperty("", sp, GUILayout.Height(128f));
            }
            else
            {
                GUIStyle style = new GUIStyle(EditorStyles.textField);
                style.wordWrap = true;

                float height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 100f);
                bool  offset = true;

                if (height > 90f)
                {
                    offset = false;
                    height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 20f);
                }
                else
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.BeginVertical(GUILayout.Width(76f));
                    GUILayout.Space(3f);
                    GUILayout.Label("Text");
                    GUILayout.EndVertical();
                    GUILayout.BeginVertical();
                }
                Rect rect = EditorGUILayout.GetControlRect(GUILayout.Height(height));

                GUI.changed = false;
                string text = EditorGUI.TextArea(rect, sp.stringValue, style);
                if (GUI.changed)
                {
                    sp.stringValue = text;
                }

                if (offset)
                {
                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }
            }

            GUI.skin.textField.wordWrap = ww;

            NGUIEditorTools.DrawPaddedProperty("Modifier", serializedObject, "mModifier");

            SerializedProperty ov = NGUIEditorTools.DrawPaddedProperty("Overflow", serializedObject, "mOverflow");
            NGUISettings.overflowStyle = (UILabel.Overflow)ov.intValue;
            if (NGUISettings.overflowStyle == UILabel.Overflow.ClampContent)
            {
                NGUIEditorTools.DrawProperty("Use Ellipsis", serializedObject, "mOverflowEllipsis", GUILayout.Width(110f));
            }

            if (NGUISettings.overflowStyle == UILabel.Overflow.ResizeFreely)
            {
                GUILayout.BeginHorizontal();
                SerializedProperty s = NGUIEditorTools.DrawPaddedProperty("Max Width", serializedObject, "mOverflowWidth");
                if (s != null && s.intValue < 1)
                {
                    GUILayout.Label("unlimited");
                }
                GUILayout.EndHorizontal();
            }

            NGUIEditorTools.DrawPaddedProperty("Alignment", serializedObject, "mAlignment");

            if (dynFont != null)
            {
                NGUIEditorTools.DrawPaddedProperty("Keep crisp", serializedObject, "keepCrispWhenShrunk");
            }

            EditorGUI.BeginDisabledGroup(mLabel.bitmapFont != null && mLabel.bitmapFont.packedFontShader);
            GUILayout.BeginHorizontal();
            SerializedProperty gr = NGUIEditorTools.DrawProperty("Gradient", serializedObject, "mApplyGradient",
                                                                 GUILayout.Width(95f));

            EditorGUI.BeginDisabledGroup(!gr.hasMultipleDifferentValues && !gr.boolValue);
            {
                NGUIEditorTools.SetLabelWidth(30f);
                NGUIEditorTools.DrawProperty("Top", serializedObject, "mGradientTop", GUILayout.MinWidth(40f));
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
                NGUIEditorTools.SetLabelWidth(50f);
                GUILayout.Space(79f);

                NGUIEditorTools.DrawProperty("Bottom", serializedObject, "mGradientBottom", GUILayout.MinWidth(40f));
                NGUIEditorTools.SetLabelWidth(80f);
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Effect", GUILayout.Width(76f));
            sp = NGUIEditorTools.DrawProperty("", serializedObject, "mEffectStyle", GUILayout.MinWidth(16f));

            EditorGUI.BeginDisabledGroup(!sp.hasMultipleDifferentValues && !sp.boolValue);
            {
                NGUIEditorTools.DrawProperty("", serializedObject, "mEffectColor", GUILayout.MinWidth(10f));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label(" ", GUILayout.Width(56f));
                    NGUIEditorTools.SetLabelWidth(20f);
                    NGUIEditorTools.DrawProperty("X", serializedObject, "mEffectDistance.x", GUILayout.MinWidth(40f));
                    NGUIEditorTools.DrawProperty("Y", serializedObject, "mEffectDistance.y", GUILayout.MinWidth(40f));
                    NGUIEditorTools.DrawPadding();
                    NGUIEditorTools.SetLabelWidth(80f);
                }
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            sp = NGUIEditorTools.DrawProperty("Float spacing", serializedObject, "mUseFloatSpacing", GUILayout.Width(100f));

            if (!sp.boolValue)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Spacing", GUILayout.Width(56f));
                NGUIEditorTools.SetLabelWidth(20f);
                NGUIEditorTools.DrawProperty("X", serializedObject, "mSpacingX", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawProperty("Y", serializedObject, "mSpacingY", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawPadding();
                NGUIEditorTools.SetLabelWidth(80f);
                GUILayout.EndHorizontal();
            }
            else
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Spacing", GUILayout.Width(56f));
                NGUIEditorTools.SetLabelWidth(20f);
                NGUIEditorTools.DrawProperty("X", serializedObject, "mFloatSpacingX", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawProperty("Y", serializedObject, "mFloatSpacingY", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawPadding();
                NGUIEditorTools.SetLabelWidth(80f);
                GUILayout.EndHorizontal();
            }

            NGUIEditorTools.DrawProperty("Max Lines", serializedObject, "mMaxLineCount", GUILayout.Width(110f));

            GUILayout.BeginHorizontal();
            sp = NGUIEditorTools.DrawProperty("BBCode", serializedObject, "mEncoding", GUILayout.Width(100f));
            EditorGUI.BeginDisabledGroup(!sp.boolValue);
            NGUIEditorTools.SetLabelWidth(60f);
            NGUIEditorTools.DrawPaddedProperty("Symbols", serializedObject, "mSymbols");
            NGUIEditorTools.SetLabelWidth(80f);
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            if (NGUIEditorTools.DrawPrefixButton("Symbol Atlas", GUILayout.Width(100f)))
            {
                ComponentSelector.Show <UIAtlas>(OnSelectAtlas);
            }
            SerializedProperty atlas = NGUIEditorTools.DrawProperty("", serializedObject, "mSymbolAtlas", GUILayout.MinWidth(20f));

            if (GUILayout.Button("Edit", GUILayout.Width(40f)))
            {
                if (atlas != null)
                {
                    UIAtlas atl = atlas.objectReferenceValue as UIAtlas;
                    NGUISettings.atlas = atl;
                    if (atl != null)
                    {
                        NGUIEditorTools.Select(atl.gameObject);
                    }
                }
            }
            GUILayout.EndHorizontal();
        }
        EditorGUI.EndDisabledGroup();
        return(isValid);
    }
Exemplo n.º 50
0
        public void UpdateMail(MailData mdb)
        {
            if (GoldList.Count != 0)
            {
                foreach (var item in GoldList)
                {
                    UnityEngine.GameObject.DestroyImmediate(item);
                }
                curMailObj.mGrid.transform.parent.gameObject.SetActive(false);
                GoldList.Clear();
            }
            if ((curMailObj != null) && (mdb != null) && (curtMailId == mdb.MailId))
            {
                curMailObj.mMailSenderTxt.text     = mdb.mailSender;
                curMailObj.mMailTitleTxt.text      = mdb.mailTitle;
                curMailObj.mMailContentTxt.text    = mdb.mailContent;
                curMailObj.mMailCreateTimeTxt.text = mdb.mailCreateTime;
                mTemp.gameObject.SetActive(true);
                string[] giftArray = mdb.mailGift.Split('|');
                for (int i = 0; i < giftArray.Length; i++)
                {
                    if (giftArray[i].Length == 0)
                    {
                        continue;
                    }
                    curMailObj.mGrid.transform.parent.gameObject.SetActive(true);
                    ResourceUnit objUnit = ResourcesManager.Instance.loadImmediate(GameConstDefine.LoadMailAttachGUI, ResourceType.PREFAB);
                    GameObject   obj     = GameObject.Instantiate(objUnit.Asset) as GameObject;
                    obj.transform.parent        = curMailObj.mGrid.transform;
                    obj.transform.localPosition = Vector3.zero;
                    obj.transform.localScale    = Vector3.one;
                    GoldList.Add(obj);
                    string[] giftStr = giftArray[i].Split(',');
                    if (giftStr.Length == 3)
                    {
                        Int32 goodsId = Convert.ToInt32(giftStr[1]);

                        MailGiftType giftType = (MailGiftType)Convert.ToInt32(giftStr[0]);
                        switch (giftType)
                        {
                        case MailGiftType.eMerchType_Gold:
                        {
                            obj.GetComponent <UISprite>().spriteName = "9";
                            obj.transform.FindChild("Label").GetComponent <UILabel>().text = giftStr[2];
                        } break;

                        case MailGiftType.eMerchType_Diamond:
                        {
                            obj.GetComponent <UISprite>().spriteName = "10";
                            obj.transform.FindChild("Label").GetComponent <UILabel>().text = giftStr[2];
                        } break;

                        //HeroBuyCfg:100001-109999
                        //  SkinCfg:110001-119999
                        //   RuneCfg:120001-129999
                        default:
                        {
                            if (goodsId >= 100001 && goodsId <= 109999)
                            {
                                HeroBuyConfigInfo buyInfo = ConfigReader.GetHeroBuyInfo(goodsId);
                                if (buyInfo != null)
                                {
                                    ResourceUnit GetMoneyUnit = ResourcesManager.Instance.loadImmediate(GameConstDefine.LoadDailyHeroIcon, ResourceType.PREFAB);
                                    UIAtlas      uia_hero     = (GetMoneyUnit.Asset as GameObject).GetComponent <UIAtlas>();

                                    obj.GetComponent <UISprite>().atlas      = uia_hero;
                                    obj.GetComponent <UISprite>().spriteName = buyInfo.DefaultIcon.ToString();
                                    obj.transform.FindChild("Label").GetComponent <UILabel>().text = giftStr[2];
                                }
                            }
                            else if (goodsId >= 120001 && goodsId <= 129999)
                            {
                                RuneConfigInfo runeInfo = ConfigReader.GetRuneFromID((uint)goodsId);
                                if (runeInfo != null)
                                {
                                    obj.GetComponent <UISprite>().spriteName = runeInfo.Icon.ToString();
                                    obj.transform.FindChild("Label").GetComponent <UILabel>().text = giftStr[2];
                                }
                            }
                            else if (goodsId >= 110001 && goodsId <= 119999)
                            {
                                HeroSkinConfigInfo skinInfo = ConfigReader.GetHeroSkinInfo(goodsId);
                                if (skinInfo != null)
                                {
                                    obj.GetComponent <UISprite>().spriteName = skinInfo.Icon.ToString();
                                    obj.transform.FindChild("Label").GetComponent <UILabel>().text = giftStr[2];
                                }
                            }
                            else if (goodsId >= 130001 && goodsId <= 139999)
                            {
                                OtherItemConfigInfo otherInfo = ConfigReader.GetOtherItemInfo((uint)goodsId);
                                if (otherInfo != null)
                                {
                                    obj.GetComponent <UISprite>().spriteName = otherInfo.icon;
                                    obj.transform.FindChild("Label").GetComponent <UILabel>().text = giftStr[2];
                                }
                            }
                        } break;
                        }
                    }
                    else
                    {
                        Debug.LogError("the error mail gift str:" + giftArray[i]);
                    }
                }
            }
            UpdateLeftMailTitleList();
            curMailObj.mGrid.repositionNow = true;
            curMailObj.mGrid.Reposition();
        }
Exemplo n.º 51
0
    private static UIAtlas CreateAtlasInternal(string atlasName, Device device, AtlasType atlasType, out List <UISpriteData> oldSpriteData)
    {
        oldSpriteData = new List <UISpriteData>();

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

        string newAtlasName     = GetAtlasName(atlasName, device, atlasType);
        string newAtlas         = string.Format("Assets{0}{1}.prefab", resourceDir, newAtlasName);
        string newAtlasMaterial = string.Format("Assets{0}{1}.mat", resourceDir, newAtlasName);

        DirectoryInfo dirInfo = new DirectoryInfo("Assets" + resourceDir);
        if (!dirInfo.Exists)
        {
#if RSATLASHELPER_DEBUG
            Debug.Log("create directory: " + resourceDir);
#endif
            dirInfo.Create();
        }


#if RSATLASHELPER_DEBUG
        Debug.Log("creating atlas assets: " + newAtlas);
#endif
        Material mat = null;
        if (atlasType != AtlasType.Ref)
        {
            mat = AssetDatabase.LoadAssetAtPath(newAtlasMaterial, typeof(Material)) as Material;
            if (mat == null)
            {
                Shader shader = Shader.Find("Unlit/Transparent Colored");
                if (shader != null)
                {
                    mat = new Material(shader);

                    AssetDatabase.CreateAsset(mat, newAtlasMaterial);
                    AssetDatabase.SaveAssets();

                    mat = AssetDatabase.LoadAssetAtPath(newAtlasMaterial, typeof(Material)) as Material;
                }
            }

            if (mat == null)
            {
                Debug.LogWarning("Error; Could not create material for atlas = " + atlasName);
                return(null);
            }
        }

        bool   saveSpriteData = true;
        Object atlasPrefab    = AssetDatabase.LoadAssetAtPath(newAtlas, typeof(GameObject));
        if (atlasPrefab == null)
        {
            atlasPrefab    = PrefabUtility.CreateEmptyPrefab(newAtlas);
            saveSpriteData = false;
        }

        if (atlasPrefab == null)
        {
            Debug.LogWarning("Error; Could not create atlas prefab for atlas = " + atlasName);
            return(null);
        }

        GameObject go = new GameObject(atlasName);

        UIAtlas atlas = go.AddComponent <UIAtlas>();
        if (atlasType != AtlasType.Ref)
        {
            atlas.spriteMaterial = mat;
        }

        if (saveSpriteData)
        {
            GameObject goOldAtlas = (GameObject)Instantiate(atlasPrefab);
            UIAtlas    oldAtlas   = goOldAtlas.GetComponent <UIAtlas>();
            GetAtlasSpriteData(ref oldAtlas, ref oldSpriteData);
            oldAtlas = null;
            DestroyImmediate(goOldAtlas);
        }

        PrefabUtility.ReplacePrefab(go, atlasPrefab, ReplacePrefabOptions.ReplaceNameBased);

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        GameObject go2 = AssetDatabase.LoadAssetAtPath(newAtlas, typeof(GameObject)) as GameObject;

        DestroyImmediate(go);
        EditorUtility.UnloadUnusedAssetsImmediate();

        UIAtlas ret = go2.GetComponent <UIAtlas>();

#if RSATLASHELPER_DEBUG
        Debug.Log("Finished creating atlas = " + ret);
#endif
        return(ret);
    }
Exemplo n.º 52
0
    /// <summary>
    /// Parse the specified JSon file, ESceneType.TYPE_LOAD sprite information for the specified atlas.
    /// </summary>

    static void LoadSpriteData(UIAtlas atlas, Hashtable decodedHash)
    {
        if (decodedHash == null || atlas == null)
        {
            return;
        }
        List <UISpriteData> oldSprites = atlas.spriteList;

        atlas.spriteList = new List <UISpriteData>();

        Hashtable frames = (Hashtable)decodedHash["frames"];

        foreach (System.Collections.DictionaryEntry item in frames)
        {
            UISpriteData newSprite = new UISpriteData();
            newSprite.name = item.Key.ToString();

            bool exists = false;

            // Check to see if this sprite exists
            foreach (UISpriteData oldSprite in oldSprites)
            {
                if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
                {
                    exists = true;
                    break;
                }
            }

            // Get rid of the extension if the sprite doesn't exist
            // The extension is kept for backwards compatibility so it's still possible to update older atlases.
            if (!exists)
            {
                newSprite.name = newSprite.name.Replace(".png", "");
                newSprite.name = newSprite.name.Replace(".tga", "");
            }

            // Extract the info we need from the TexturePacker json file, mainly uvRect and size
            Hashtable table = (Hashtable)item.Value;
            Hashtable frame = (Hashtable)table["frame"];

            int frameX = int.Parse(frame["x"].ToString());
            int frameY = int.Parse(frame["y"].ToString());
            int frameW = int.Parse(frame["w"].ToString());
            int frameH = int.Parse(frame["h"].ToString());

            // Read the rotation value
            //newSprite.rotated = (bool)table["rotated"];

            newSprite.x      = frameX;
            newSprite.y      = frameY;
            newSprite.width  = frameW;
            newSprite.height = frameH;

            // Support for trimmed sprites
            Hashtable sourceSize = (Hashtable)table["sourceSize"];
            Hashtable spriteSize = (Hashtable)table["spriteSourceSize"];

            if (spriteSize != null && sourceSize != null)
            {
                // TODO: Account for rotated sprites
                if (frameW > 0)
                {
                    int spriteX = int.Parse(spriteSize["x"].ToString());
                    int spriteW = int.Parse(spriteSize["w"].ToString());
                    int sourceW = int.Parse(sourceSize["w"].ToString());

                    newSprite.paddingLeft  = spriteX;
                    newSprite.paddingRight = sourceW - (spriteX + spriteW);
                }

                if (frameH > 0)
                {
                    int spriteY = int.Parse(spriteSize["y"].ToString());
                    int spriteH = int.Parse(spriteSize["h"].ToString());
                    int sourceH = int.Parse(sourceSize["h"].ToString());

                    newSprite.paddingTop    = spriteY;
                    newSprite.paddingBottom = sourceH - (spriteY + spriteH);
                }
            }

            // If the sprite was present before, see if we can copy its inner rect
            foreach (UISpriteData oldSprite in oldSprites)
            {
                if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
                {
                    newSprite.borderLeft   = oldSprite.borderLeft;
                    newSprite.borderRight  = oldSprite.borderRight;
                    newSprite.borderBottom = oldSprite.borderBottom;
                    newSprite.borderTop    = oldSprite.borderTop;
                }
            }

            // Add this new sprite
            atlas.spriteList.Add(newSprite);
        }

        // Sort imported sprites alphabetically
        atlas.spriteList.Sort(CompareSprites);
        Debug.Log("Imported " + atlas.spriteList.Count + " sprites");
    }
Exemplo n.º 53
0
    /// <summary>
    /// Parse the specified JSon file, loading sprite information for the specified atlas.
    /// </summary>

    public static void LoadSpriteData(UIAtlas atlas, TextAsset asset)
    {
        if (asset == null || atlas == null)
        {
            return;
        }

        string    jsonString  = asset.text;
        Hashtable decodedHash = jsonDecode(jsonString) as Hashtable;

        if (decodedHash == null)
        {
            Debug.LogWarning("Unable to parse Json file: " + asset.name);
            return;
        }

        atlas.coordinates = UIAtlas.Coordinates.Pixels;
        List <UIAtlas.Sprite> oldSprites = atlas.spriteList;

        atlas.spriteList = new List <UIAtlas.Sprite>();

        Hashtable frames = (Hashtable)decodedHash["frames"];

        foreach (System.Collections.DictionaryEntry item in frames)
        {
            UIAtlas.Sprite newSprite = new UIAtlas.Sprite();
            newSprite.name = item.Key.ToString();

            bool exists = false;

            // Check to see if this sprite exists
            foreach (UIAtlas.Sprite oldSprite in oldSprites)
            {
                if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
                {
                    exists = true;
                    break;
                }
            }

            // Get rid of the extension if the sprite doesn't exist
            // The extension is kept for backwards compatibility so it's still possible to update older atlases.
            if (!exists)
            {
                newSprite.name = newSprite.name.Replace(".png", "");
                newSprite.name = newSprite.name.Replace(".tga", "");
            }

            // Extract the info we need from the TexturePacker json file, mainly uvRect and size
            Hashtable table = (Hashtable)item.Value;
            Hashtable frame = (Hashtable)table["frame"];

            int frameX = int.Parse(frame["x"].ToString());
            int frameY = int.Parse(frame["y"].ToString());
            int frameW = int.Parse(frame["w"].ToString());
            int frameH = int.Parse(frame["h"].ToString());

            // Read the rotation value
            newSprite.rotated = (bool)table["rotated"];

            // Fill in the proper values
            if (newSprite.rotated)
            {
                newSprite.outer = new Rect(frameX, frameY, frameH, frameW);
                newSprite.inner = new Rect(frameX, frameY, frameH, frameW);
            }
            else
            {
                newSprite.outer = new Rect(frameX, frameY, frameW, frameH);
                newSprite.inner = new Rect(frameX, frameY, frameW, frameH);
            }

            // Support for trimmed sprites
            Hashtable sourceSize = (Hashtable)table["sourceSize"];
            Hashtable spriteSize = (Hashtable)table["spriteSourceSize"];

            if (spriteSize != null && sourceSize != null)
            {
                // TODO: Account for rotated sprites
                if (frameW > 0)
                {
                    float spriteX = int.Parse(spriteSize["x"].ToString());
                    float spriteW = int.Parse(spriteSize["w"].ToString());
                    float sourceW = int.Parse(sourceSize["w"].ToString());

                    newSprite.paddingLeft  = spriteX / frameW;
                    newSprite.paddingRight = (sourceW - (spriteX + spriteW)) / frameW;
                }

                if (frameH > 0)
                {
                    float spriteY = int.Parse(spriteSize["y"].ToString());
                    float spriteH = int.Parse(spriteSize["h"].ToString());
                    float sourceH = int.Parse(sourceSize["h"].ToString());

                    newSprite.paddingTop    = spriteY / frameH;
                    newSprite.paddingBottom = (sourceH - (spriteY + spriteH)) / frameH;
                }
            }

            // If the sprite was present before, see if we can copy its inner rect
            foreach (UIAtlas.Sprite oldSprite in oldSprites)
            {
                if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
                {
                    CopyInnerRect(oldSprite, newSprite);
                }
            }

            // Add this new sprite
            atlas.spriteList.Add(newSprite);
        }

        // Sort imported sprites alphabetically
        atlas.spriteList.Sort(CompareSprites);
        Debug.Log("Imported " + atlas.spriteList.Count + " sprites");

        // Unload the asset
        asset = null;
        Resources.UnloadUnusedAssets();
    }
Exemplo n.º 54
0
    /// <summary>
    /// Extract sprites from the atlas, adding them to the list.
    /// </summary>

    static void ExtractSprites(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        // Make the atlas texture readable
        Texture2D atlasTex = NGUIEditorTools.ImportTexture(atlas.texture, true, false);

        if (atlasTex != null)
        {
            atlas.coordinates = UIAtlas.Coordinates.Pixels;

            Color32[]             oldPixels = null;
            int                   oldWidth  = atlasTex.width;
            int                   oldHeight = atlasTex.height;
            List <UIAtlas.Sprite> list      = atlas.spriteList;

            foreach (UIAtlas.Sprite asp in list)
            {
                bool found = false;

                foreach (SpriteEntry se in sprites)
                {
                    if (asp.name == se.name)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    // Read the atlas
                    if (oldPixels == null)
                    {
                        oldPixels = atlasTex.GetPixels32();
                    }

                    Rect rect = asp.outer;
                    rect.xMin = Mathf.Clamp(rect.xMin, 0f, oldWidth);
                    rect.yMin = Mathf.Clamp(rect.yMin, 0f, oldHeight);
                    rect.xMax = Mathf.Clamp(rect.xMax, 0f, oldWidth);
                    rect.yMax = Mathf.Clamp(rect.yMax, 0f, oldHeight);

                    int newWidth  = Mathf.RoundToInt(rect.width);
                    int newHeight = Mathf.RoundToInt(rect.height);
                    if (newWidth == 0 || newHeight == 0)
                    {
                        continue;
                    }

                    Color32[] newPixels = new Color32[newWidth * newHeight];
                    int       xmin      = Mathf.RoundToInt(rect.x);
                    int       ymin      = Mathf.RoundToInt(oldHeight - rect.yMax);

                    for (int y = 0; y < newHeight; ++y)
                    {
                        for (int x = 0; x < newWidth; ++x)
                        {
                            int newIndex = y * newWidth + x;
                            int oldIndex = (ymin + y) * oldWidth + (xmin + x);
                            newPixels[newIndex] = oldPixels[oldIndex];
                        }
                    }

                    // Create a new sprite
                    SpriteEntry sprite = new SpriteEntry();
                    sprite.name             = asp.name;
                    sprite.temporaryTexture = true;
                    sprite.tex  = new Texture2D(newWidth, newHeight);
                    sprite.rect = new Rect(0f, 0f, newWidth, newHeight);
                    sprite.tex.SetPixels32(newPixels);
                    sprite.tex.Apply();

                    // Min/max coordinates are in pixels
                    sprite.minX = Mathf.RoundToInt(asp.paddingLeft * newWidth);
                    sprite.maxX = Mathf.RoundToInt(asp.paddingRight * newWidth);
                    sprite.minY = Mathf.RoundToInt(asp.paddingBottom * newHeight);
                    sprite.maxY = Mathf.RoundToInt(asp.paddingTop * newHeight);

                    sprites.Add(sprite);
                }
            }
        }

        // The atlas no longer needs to be readable
        NGUIEditorTools.ImportTexture(atlas.texture, false, false);
    }
Exemplo n.º 55
0
    private List <string> _areadyDealList;//已处理的hash

    /// <summary>
    /// 重复图集检测
    /// </summary>
    private void OnSpriteCheckGUI()
    {
        GUILayout.BeginHorizontal();
        _ImgRoot = EditorGUILayout.TextField("根目录:", _ImgRoot, GUILayout.Width(300));
        if (GUILayout.Button("检测全部", GUILayout.Height(50f)))
        {
            OnCheckSameFile();
        }
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        _editPrefab = EditorGUILayout.ObjectField("图集:", _editPrefab, typeof(UIAtlas), false, GUILayout.Width(300)) as UIAtlas;
        if (GUILayout.Button("根据图集检测", GUILayout.Height(50f)))
        {
            OnCheckSameFile(_editPrefab);
        }
        GUILayout.EndHorizontal();

        if (_sameFolderExpand == null)
        {
            _sameFolderExpand = new Dictionary <string, bool>();
        }
        if (_selResultExpand == null)
        {
            _selResultExpand = new Dictionary <string, bool>();
        }
        if (_ignoreResetList == null)
        {
            _ignoreResetList = new List <string>();
        }
        if (_areadyDealList == null)
        {
            _areadyDealList = new List <string>();
        }

        if (_sameCount > 0)
        {
            EditorGUILayout.BeginVertical("HelpBox", GUILayout.Width(700f));
            {
                GUILayout.Space(10f);
                GUILayout.Label(string.Format("Result: 重复总条目数:{0}  UI引用总数:{1} 已处理条目数:{2}", _sameCount, _refCount, _areadyDealList.Count));
                GUILayout.Space(5f);
                _sameHashScroll = EditorGUILayout.BeginScrollView(_sameHashScroll, GUILayout.MinHeight(350f));
                foreach (string hash in _hash2Filenames.Keys)
                {
                    List <string> filenames = _hash2Filenames[hash];
                    if (filenames.Count <= 1)
                    {
                        continue;
                    }

                    if (!_sameFolderExpand.ContainsKey(hash))
                    {
                        _sameFolderExpand.Add(hash, false);
                    }

                    bool bDeal = _areadyDealList.Contains(hash);

                    string name = string.Format("png数:{0} UI引用总数:{1}",
                                                filenames.Count, GetRefUICount(filenames));
                    if (bDeal)
                    {
                        name += "  已处理";
                    }

                    GUI.backgroundColor = bDeal ? Color.green : Color.white;
                    GUI.color           = bDeal ? Color.green : Color.white;
                    if (EditorGUILayout.Foldout(_sameFolderExpand[hash], name))
                    {
                        //收起
                        if (_preSelectFolder != null && hash != _preSelectFolder &&
                            _sameFolderExpand.ContainsKey(_preSelectFolder))
                        {
                            _sameFolderExpand[_preSelectFolder] = false;
                            _replaceAtlas = null;
                            _replaceName  = null;
                            _selFilename  = "";
                        }
                        _preSelectFolder        = hash;
                        _sameFolderExpand[hash] = true;
                    }
                    else
                    {
                        _sameFolderExpand[hash] = false;
                    }
                    GUI.backgroundColor = Color.white;
                    GUI.color           = Color.white;

                    if (_sameFolderExpand[hash])
                    {
                        foreach (var png in filenames)
                        {
                            GUILayout.Space(-1f);
                            GUI.backgroundColor = !png.Equals(_selFilename) ? Color.white : new Color(0.8f, 0.8f, 0.8f);
                            GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                            GUI.backgroundColor = Color.white;
                            string sText = png.Replace(_ImgRoot + "/", "") + " "
                                           + string.Format("UI引用数:{0}", GetRefUICount(png));
                            //GUILayout.Label(sText);
                            if (GUILayout.Button(sText, "OL TextField", GUILayout.Height(20f)))
                            {
                                _selFilename = png;
                            }

                            if (GUILayout.Button("复制sprite", GUILayout.Width(85f)))
                            {
                                string spriteName = png.Substring(png.LastIndexOf("/") + 1,
                                                                  png.LastIndexOf(".") - png.LastIndexOf("/") - 1);
                                NGUITools.clipboard = spriteName;
                            }

                            GUI.backgroundColor = _ignoreResetList.Contains(png) ? Color.green : Color.white;
                            sText = _ignoreResetList.Contains(png) ? "取消忽略" : "忽略";
                            if (GUILayout.Button(sText, GUILayout.Width(85f)))
                            {
                                if (_ignoreResetList.Contains(png))
                                {
                                    _ignoreResetList.Remove(png);
                                }
                                else
                                {
                                    _ignoreResetList.Add(png);
                                }
                            }
                            GUI.backgroundColor = Color.white;

                            if (GUILayout.Button("设置为目标", GUILayout.Width(100f)))
                            {
                                Debug.Log("图集目录:" + _filename2AtlasPath[png]);
                                _replaceAtlas = AssetDatabase.LoadAssetAtPath(_filename2AtlasPath[png], typeof(UIAtlas)) as UIAtlas;
                                _replaceName  = GetSpriteName(png);
                            }
                            GUILayout.EndHorizontal();
                        }
                        GUILayout.BeginHorizontal();
                        GUILayout.Space(15f);
                        _replaceAtlas = (UIAtlas)EditorGUILayout.ObjectField("目标图集:", _replaceAtlas, typeof(UIAtlas), false);
                        _replaceName  = EditorGUILayout.TextField("spriteName:", _replaceName);
                        if (GUILayout.Button("确认转移", GUILayout.Width(100f)))
                        {
                            CommitResetSame(hash);
                        }
                        GUILayout.EndHorizontal();
                    }
                }
                EditorGUILayout.EndScrollView();
            }
            EditorGUILayout.EndVertical();

            if (!string.IsNullOrEmpty(_selFilename))
            {
                var    manager = HitManager.GetManager(_selFilename);
                string sResult = string.Format("UI引用{0} {1}", manager.hitTotal, _selFilename);
                GUILayout.BeginVertical();
                if (EditorHelper.DrawHeader(sResult, "pngResult", false, false))
                {
                    _pngResultPos = EditorGUILayout.BeginScrollView(_pngResultPos, GUILayout.MinHeight(120f));
                    foreach (HitData data in manager.hitDataList)
                    {
                        string keyName = data.prefabName + _selFilename;
                        if (!_selResultExpand.ContainsKey(keyName))
                        {
                            _selResultExpand.Add(keyName, false);
                        }

                        string sText = data.prefabName + string.Format("   引用数:{0}", data.hitCount);
                        if (EditorGUILayout.Foldout(_selResultExpand[keyName], sText))
                        {
                            GUILayout.BeginVertical();
                            foreach (string path in data.hitPathList)
                            {
                                GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
                                GUILayout.Space(30f);
                                GUILayout.Label(path);
                                GUILayout.EndHorizontal();
                            }
                            _selResultExpand[keyName] = true;
                            GUILayout.EndVertical();
                        }
                        else
                        {
                            _selResultExpand[keyName] = false;
                        }
                    }
                    EditorGUILayout.EndScrollView();
                }

                Texture img = AssetDatabase.LoadAssetAtPath(_selFilename, typeof(Texture)) as Texture;
                GUILayout.Space(20);
                GUILayout.BeginHorizontal();
                GUILayout.Space(60);
                GUILayout.Box(img);
                GUILayout.EndHorizontal();
                GUILayout.EndVertical();
            }
        }

        GUILayout.BeginVertical();
        EditorGUILayout.Space();
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("只处理图集目录下的imgs目录,以其它名字命名的不处理,比如img");
        EditorGUILayout.LabelField("含有忽略的目录名,见_ignoreFolderList列表。");
        EditorGUILayout.LabelField("需自行处理的:");
        EditorGUILayout.LabelField("1、确定代码中的引用");
        EditorGUILayout.LabelField("2、UI.prefab的替换为优化depth,可能是draw call增加");
        GUI.color = Color.red;
        EditorGUILayout.LabelField("3、九宫切图");
        GUI.color = Color.white;
        GUILayout.EndVertical();
    }
Exemplo n.º 56
0
    private void OnGUI()
    {
        GUILayout.BeginHorizontal();
        NIEditorUtility.DrawAuthorSummary();
        GUILayout.Space(5);
        if (GUILayout.Button("刷新", GUILayout.MaxWidth(70)))
        {
            Refresh();
            return;
        }
        GUILayout.Space(5);
        GUILayout.Label("重新获取待打包图片文件夹", EditorStyles.boldLabel, GUILayout.MaxWidth(350));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Space(10f);
        GUILayout.BeginVertical();
        GUILayout.Space(10f);
        GUI.backgroundColor = new Color32(150, 200, 255, 255);
        //未创建的在前,已创建的在后
        dirList.Sort((string a, string b) =>
        {
            string aPath = a.Replace("Z_RES/Atlas/", "Assets/AtlasRes/");
            string bPath = b.Replace("Z_RES/Atlas/", "Assets/AtlasRes/");
            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/AtlasRes/");
            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, 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(PREFAB_PATH + atlasName + "/" + atlasName + "Atlas" + ".prefab"))
                    {
                        UIAtlas atlas    = Resources.Load <UIAtlas>("Atlas/" + atlasName + "/" + atlasName + "Atlas");
                        string  textPath = CONFIG_PATH + atlasName + "/" + 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();
    }
Exemplo n.º 57
0
    void OnGUI()
    {
        if (Selection.activeObject)
        {
            Sprite sprite = Selection.activeObject as Sprite;
            if (sprite)
            {
                if (!sprites.ContainsKey(sprite.name))
                {
                    sprites.Add(sprite.name, new SpriteData(sprite.name, sprite));
                }
                else
                {
                    if (sprites[sprite.name].Sprite != sprite)
                    {
                        sprites[sprite.name].Sprite   = sprite;
                        sprites[sprite.name].IsChange = true;
                    }
                }
            }
        }

        EditorGUILayout.BeginVertical();

        float posX = 10;
        float posY = 10;

        Rect rect = new Rect(posX, posY, 500, 20);

        uiAtlas = EditorGUI.ObjectField(rect, new GUIContent("Atlas:"), uiAtlas, typeof(UIAtlas), false) as UIAtlas;

        if (uiAtlas)
        {
            foreach (var item in uiAtlas.GetSprites())
            {
                if (!sprites.ContainsKey(item.Key))
                {
                    sprites.Add(item.Key, new SpriteData(item.Key, item.Value));
                }
            }
        }
        else
        {
            sprites.Clear();
        }

        posY += 20;
        rect  = new Rect(posX, posY, 100, 50);
        GUILayout.BeginArea(rect);
        using (var h = new EditorGUILayout.HorizontalScope("Button"))
        {
            if (GUI.Button(h.rect, GUIContent.none))
            {
                CreateNewAtlas();
            }
            GUIStyle style = new GUIStyle();
            style.alignment = TextAnchor.MiddleCenter;
            GUILayout.Label("New Atlas", style);
        }
        GUILayout.EndArea();

        posY += 50;

        pos = EditorGUILayout.BeginScrollView(new Vector2(posX, posY));

        GUILayout.BeginArea(new Rect(pos, new Vector2(600, 250)));

        EditorGUILayout.BeginVertical();

        List <string> curSprites = new List <string>(sprites.Keys);

        foreach (var sp in curSprites)
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.TextField("Sprite:", sp, GUILayout.Width(500));

            if (GUILayout.Button(new GUIContent("Delete")))
            {
                sprites.Remove(sp);
                DeleteSprite(sp);
            }
            EditorGUILayout.EndHorizontal();
        }

        EditorGUILayout.EndVertical();

        GUILayout.EndArea();

        EditorGUILayout.EndScrollView();

        using (var h = new EditorGUILayout.HorizontalScope("Button"))
        {
            if (GUI.Button(h.rect, GUIContent.none))
            {
                if (uiAtlas)
                {
                    AddOrUpdateAtlas(uiAtlas.name);
                }
                else
                {
                    Debug.LogError("Atlas can't be null!");
                }
            }
            GUIStyle style = new GUIStyle();
            style.alignment = TextAnchor.MiddleCenter;
            GUILayout.Label("Add/Update", style);
        }

        EditorGUILayout.EndVertical();

        this.Repaint();
    }
Exemplo n.º 58
0
    //resName:文件夹名字->Common
    private void SetMeta(string resName)
    {
        string pngPath   = CONFIG_PATH + resName + "/" + resName + ".png";
        string alphaPath = CONFIG_PATH + resName + "/" + resName + "_alpha" + ".png";
        string textPath  = CONFIG_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(PREFAB_PATH + resName + "/" + 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(Application.dataPath + "/AtlasRes/" + 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();

            if (!Directory.Exists(PREFAB_PATH + resName))
            {
                Directory.CreateDirectory(PREFAB_PATH + resName);
            }
            PrefabUtility.CreatePrefab("Assets/Resources/Atlas/" + resName + "/" + obj.name + ".prefab", obj, ReplacePrefabOptions.ReplaceNameBased);
            GameObject.DestroyImmediate(obj);
        }
    }
Exemplo n.º 59
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);
                                }
                            }
                        }
                    }
                    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;
                }
            }
        }
    }
Exemplo n.º 60
0
 public void DisplayDetail(FrontiersInterface user, string name, string detailText, string iconName, UIAtlas iconAtlas, Color iconColor, Color iconBackgroundColor)
 {
     ScrollBar.scrollValue = 0f;
     Show();
     NameLabel.text        = name;
     DetailTextLabel.color = Colors.Get.MenuButtonTextColorDefault;
     DetailTextLabel.text  = detailText;
     if (string.IsNullOrEmpty(iconName) || iconAtlas == null)
     {
         Icon.enabled           = false;
         IconBackground.enabled = false;
     }
     else
     {
         Icon.enabled           = true;
         IconBackground.enabled = true;
         Icon.atlas             = iconAtlas;
         Icon.spriteName        = iconName;
         Icon.color             = iconColor;
         IconBackground.color   = iconBackgroundColor;
     }
     ShowDoppleganger = false;
     RefreshDoppleganger();
     LastUser = user;
 }